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

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_;
    FILE* file_{};
    TransState trans_state_{TRANS_FAILED};
};

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& cmd);
    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& list_file, int index);
    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 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_;

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

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

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