#pragma once
#include <fstream>
#include <memory>
#include <mutex>
#include <net_base.h>
#include <of_util.h>
#include <string>
#include <util.h>
#include <vector>
#include <filecomplete.h>

using namespace ofen;
struct DownClientInfo {
    std::vector<std::string> files;
    std::string id;
};

enum TransState {
    TRANS_FAILED,
    TRANS_ING,
    TRANS_REDAY,
    TRANS_DONE,
    TRANS_BREAK
};

struct TransInfomation {
    std::string cur_remote_id_;
    std::string cur_remote_file_;
    std::string cur_file_;
    std::fstream file_{};
    TransState trans_state_{TRANS_FAILED};
};

constexpr int down_check_wait = 100;   // millsec
class CClient
{
public:
    CClient(const std::shared_ptr<spdlog::logger>& logger);
    ~CClient();

public:
    void run(const std::string& ip, const std::string& port);

public:
    bool get_task_list();
    bool down_task(const std::string& param);
    bool up_task(const std::string& param);
    bool cancel_task();
    bool down_one_file(const std::string& id, const std::string& file, const std::string& local_dir = "");
    void report_trans_ret(TransState state, const std::string& key = "");
    bool request_update_list(const std::string& param);
    bool check_update_list(const std::string& content, std::map<std::string, std::string>& files);
    bool down_update_file(std::map<std::string, std::string> files);

private:
    bool send_frame(CFrameBuffer* buf);

private:
    void handle_frame(CFrameBuffer* buf);
    void send_file_data_th(const char* keys);
    void hearts();
    void judget_down_active();

private:
    std::mutex mutex_;
    std::mutex send_mut_;
    std::string work_key_;
    std::thread hearts_;
    CThreadSleep sleep_;
    bool th_run_{false};
    bool will_receive_{false};
    bool downloading_{false};
    std::shared_ptr<spdlog::logger> logger_;
    asio::io_context io_context_;
    std::shared_ptr<CTcpClient> client_;
    std::vector<std::string> supported_;
    std::map<int, std::shared_ptr<DownClientInfo>> task_list_;
    std::shared_ptr<TransInfomation> down_;
    std::vector<std::thread> ths_;
    std::map<std::string, std::shared_ptr<TransInfomation>> up_;
    std::thread th_down_active_;
    long long cur_file_size_{};
    long long cur_down_size_{};

private:
    std::string update_list_content_;
    std::string list_file_;
    std::string list_serve_id_;
    std::thread update_list_th_;
    std::string own_id_{};
};

class CFileOpr
{
public:
    CFileOpr();
    ~CFileOpr();

public:
    static std::vector<std::string> get_file_list(const std::string& input);
};