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

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_{};
    uint16_t permissions{};
    uint16_t remote_plat{};
    TransState trans_state_{TRANS_FAILED};
};

constexpr int down_check_wait = 100;   // millsec
class CClient
{
public:
    CClient();
    ~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(const 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();
    std::string variable_handle(const std::string& task_list_path, const std::string& source, bool is_send);
    std::string handle_user_select(const std::unordered_map<int, std::string>& source);

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};
    asio::io_context io_context_;
    std::shared_ptr<CTcpClient> client_;
    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 list_file_;
    std::string list_serve_id_;
    std::thread update_list_th_;
    std::string own_id_{};
};

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

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