#ifndef IY_MODBUS_TCP_SERVER_H
#define IY_MODBUS_TCP_SERVER_H

#include <functional>
#include <vector>
#include <thread>
#include <mutex>
#include <atomic>
#include <memory>
#include <unordered_map>

class IYModbusTCPServer {
public:
    // 错误代码枚举
    enum class ErrorCode {
        SUCCESS = 0,
        ILLEGAL_FUNCTION = 1,
        ILLEGAL_DATA_ADDRESS = 2,
        ILLEGAL_DATA_VALUE = 3,
        SERVER_FAILURE = 4,
        ACKNOWLEDGE = 5,
        SERVER_BUSY = 6,
        NEGATIVE_ACKNOWLEDGE = 7,
        MEMORY_PARITY = 8,
        GATEWAY_PATH_UNAVAILABLE = 10,
        GATEWAY_TARGET_FAILED = 11
    };

    // 回调函数类型定义
    // 写线圈回调函数：unitId, startAddress, quantity, values -> ErrorCode
    using WriteCoilsCallback = std::function<ErrorCode(uint8_t, uint16_t, uint16_t, const uint8_t*)>;
    
    // 写保持寄存器回调函数：unitId, startAddress, quantity, values -> ErrorCode  
    using WriteRegistersCallback = std::function<ErrorCode(uint8_t, uint16_t, uint16_t, const uint16_t*)>;

public:
    virtual ~IYModbusTCPServer() = default;

    static bool CreateInstance(IYModbusTCPServer** ppModbusTCPServer);

    // 启动/停止服务器
    virtual bool start(int port = 502, int maxConnections = 10) = 0;
    virtual void stop() = 0;
    
    // 设置回调函数
    virtual void setWriteCoilsCallback(WriteCoilsCallback callback) = 0;
    virtual void setWriteRegistersCallback(WriteRegistersCallback callback) = 0;
    
    // 更新数据接口 - 线程安全
    virtual void updateCoil(uint16_t address, bool value) = 0;
    virtual void updateCoils(uint16_t startAddress, const std::vector<bool>& values) = 0;
    virtual void updateDiscreteInput(uint16_t address, bool value) = 0;
    virtual void updateDiscreteInputs(uint16_t startAddress, const std::vector<bool>& values) = 0;
    virtual void updateHoldingRegister(uint16_t address, uint16_t value) = 0;
    virtual void updateHoldingRegisters(uint16_t startAddress, const std::vector<uint16_t>& values) = 0;
    virtual void updateInputRegister(uint16_t address, uint16_t value) = 0;
    virtual void updateInputRegisters(uint16_t startAddress, const std::vector<uint16_t>& values) = 0;

};

#endif // MODBUS_TCP_SERVER_H 