#ifndef MEASUREMENTDATAUTILS_H
#define MEASUREMENTDATAUTILS_H

#include "networkCommon.h"
#include <QObject>
#include <QWebSocket>
#include <QTimer>

struct MeasurementDataPoint
{
    qint64 timestamp;
    double value;

    MeasurementDataPoint() : timestamp(0), value(0.0)
    {}
    MeasurementDataPoint(qint64 st, double val) : timestamp(st), value(val)
    {}

    bool operator < (const MeasurementDataPoint& other) const
    {
        return timestamp < other.timestamp;
    }

    bool operator == (const MeasurementDataPoint& other) const
    {
        return timestamp == other.timestamp;
    }
};

// 用于QHash的哈希函数
inline size_t qHash(const MeasurementDataPoint& dp, size_t seed = 0)
{
    return qHash(dp.timestamp, seed);
}

/**
 * @brief 本地数据存储
 *
 * 存储接收到的实时数据，具有去除重复数据功能
 */
class MeasurementData
{
public:
    explicit MeasurementData(const QString& id);

    int insertData(const QVector<MeasurementDataPoint>& newData);
    QVector<MeasurementDataPoint> getLastestData(int count);
    QVector<MeasurementDataPoint> getDataInRange(qint64 startTime, qint64 endTime);
    void cleanupOldData(qint64 cutoffTime);

private:
    QString m_id;
    QSet<qint64> m_timestamps; //用于快速查找是否存在该时间戳的数据
    QMap<qint64, double> m_data; //按时间戳对数据点进行排序
    qint64 m_latestTimestamp;
};

/**
 * @brief WebSocket数据客户端
 *
 * 负责与后台数据服务建立WebSocket连接，接收实时数据
 */
class WebSocketClient : public QObject
{
    Q_OBJECT

public:
    explicit WebSocketClient(QObject* parent = nullptr);
    ~WebSocketClient();

    //连接管理
    bool connectToServer(const QUrl& url);
    void disconnectFromServer();
    //bool isConnected();

    //数据配置
    void setReconnectInterval(int intervalMs);
    void setMaxReconnectAttempts(int maxAttempts);

signals:
    void dataReceived(const QString& dataMsg);

private slots:
    void onConnected();
    void onDisconnected();
    void onError(QAbstractSocket::SocketError error);
    void onTextMessageReceived(const QString& message);
    void onReconnectTimeout();
    void resetReconnect();

private:
    void setupWebSocket();
    void cleanupWebSocket();
    void scheduleReconnect();

    QWebSocket* m_webSocket;
    QUrl m_serverUrl;

    //重连相关
    QTimer m_reconnectTimer;
    int m_reconnectInterval;
    int m_reconnectAttempts;
    int m_maxReconnectAttempts;

    // 状态
    bool m_connected;
    ConnectionStatus m_connectionStatus;
};

#endif
