#pragma once
#include <list>
#include <net_base.h>
#include <of_util.h>
#include <string>
#include <util.h>
#include <vector>
#include <chrono>

using namespace ofen;
using high_c = std::chrono::time_point<std::chrono::high_resolution_clock>;
struct ClientCache {
    std::shared_ptr<asio::ip::tcp::socket> socket_;
    CMutBuffer buffer_{};
    std::array<char, g_BuffSize> tmp_buf_{};
    std::string task_{};
    std::string task_time_{};
    std::string online_time_{};
    high_c last_active_time_;
    FrameType cur_type_{TYPE_DEFAULT};
};
struct TaskList {
    std::string id_{};
    std::string task_{};
    std::string task_time_{};
    std::string online_time_{};
};

class CTcpServer
{
public:
    CTcpServer(asio::io_context& io_context, const std::shared_ptr<spdlog::logger>& logger);
    ~CTcpServer();

public:
    bool start(unsigned short port);
    void stop();

private:
    std::vector<TaskList> get_clients();
    void get_client_list(CFrameBuffer** buf);

private:
    void trans_data(CFrameBuffer* buf);
    bool check_double(CFrameBuffer* buf, std::shared_ptr<ClientCache>& fcli,
                      std::shared_ptr<ClientCache>& tcli);

private:
    void accept_client();
    void th_client(std::shared_ptr<asio::ip::tcp::socket> socket, const std::string& client_key);
    bool send_frame(std::shared_ptr<asio::ip::tcp::socket> socket, CFrameBuffer* buf);
    void monitor_idle();

private:
    bool th_run_{false};
    asio::io_context& io_context_;
    asio::ip::tcp::acceptor acceptor_;
    std::shared_ptr<spdlog::logger> logger_;
    std::map<std::string, std::shared_ptr<ClientCache>> client_map_;
    std::map<std::string, std::thread> client_threads_;
    std::mutex cli_mut_;
    std::mutex buf_mut_;
    std::thread th_monitor_idle_;
    std::string server_ip_;
    CThreadSleep sleep_;
};