#include <uv.h>
#include <string>
#include <vector>
#include <memory>
#include <unordered_map>
#include <mutex>

// 测点信息结构
struct PointInfo {
    std::string point_id;       // 测点ID
    std::string name;           // 测点名称
    std::string device_id;      // 所属装置ID
    double PT1;                 // 电压变比1
    double PT2;                 // 电压变比2
    double CT1;                 // 电流变比1
    double CT2;                 // 电流变比2
};

// 装置信息结构
struct DeviceInfo {
    std::string device_id;      // 装置ID
    std::string name;           // 装置名称
    std::string model;          // 装置型号
    std::string mac;            // 装置MAC地址
    int status;                 // 运行状态 (0: 离线, 1: 在线)
    std::vector<PointInfo> points; // 下属测点
};

enum class ConnectionState {
    DISCONNECTED,
    CONNECTING,
    CONNECTED
};

class ClientContext {
public:
    uv_loop_t* loop;
    uv_tcp_t client;
    uv_timer_t timer;
    uv_timer_t reconnect_timer;
    ConnectionState state;
    int reconnect_attempts;
    volatile bool shutdown;
    DeviceInfo device_info;  // 装置信息

    ClientContext(uv_loop_t* loop, const DeviceInfo& device, int index);
    ~ClientContext();

    void init_tcp();
    void start_timer();
    void start_reconnect_timer(int delay);
    void stop_timers();
    void close_handles();
    void append_and_process_data(const char* data, size_t len);
    void put_packet_into_queue(const std::vector<unsigned char>& packet);

private:
    int index_;

private:
    std::vector<unsigned char> recv_buffer_;   // 接收数据缓冲区
    std::mutex buffer_mutex_;                  // 缓冲区互斥锁
    void process_buffer();
};

class ClientManager {
public:
    static ClientManager& instance() {
        static ClientManager inst;
        return inst;
    }

    // 设置事件循环
    void set_loop(uv_loop_t* loop) {
        std::lock_guard<std::mutex> lock(mutex_);
        loop_ = loop;
    }

    void add_device(const DeviceInfo& device);
    void remove_device(const std::string& device_id);
    bool send_to_device(const std::string& identifier, const unsigned char* data, size_t size);
    void stop_all();
    // 获取客户端数量
    size_t client_count() {
        std::lock_guard<std::mutex> lock(mutex_);
        return clients_.size();
    }

private:
    ClientManager() : loop_(nullptr) {}
    std::unordered_map<std::string, std::unique_ptr<ClientContext>> clients_;
    std::mutex mutex_;
    uv_loop_t* loop_;  // 事件循环指针
};

// 函数声明
void start_client_connect(const std::vector<DeviceInfo>& devices);
void send_binary_data(ClientContext* ctx, const unsigned char* data, size_t data_size);
void on_timer(uv_timer_t* handle);
void try_reconnect(uv_timer_t* timer);
void on_connect(uv_connect_t* req, int status);
void on_close(uv_handle_t* handle);
void init_clients(uv_loop_t* loop, const std::vector<DeviceInfo>& devices);
void stop_all_clients();