#ifndef MYNETMANAGER_H
#define MYNETMANAGER_H

#include <QString>
#include <QAuthenticator>
#include <QNetworkAccessManager>
#include <QTimer>
#include <atomic>
#include <QNetworkReply>

typedef enum
{
    NET_DISCONNECT,
    NET_CONNECTING = 1,
    NET_CONNECTED,
}NetState;

class QNetworkReply;
class MyNetManager : public QObject
{
    Q_OBJECT

public:

    explicit MyNetManager(QObject *parent = nullptr);
    ~MyNetManager();
    /**
     * @brief 设置连接IP地址
     * @param ip
     */
    void SetIp(QString ip);
    /**
     * @brief 设置温度参数
     * @param reflectiveTemperature
     * @param emissivity
     * @param distance
     * @return
     */
    bool SetTempraturePara(uint16_t reflectiveTemperature,float emissivity,uint16_t distance) ;
    /**
     * @brief 设置告警参数
     * @param alert
     * @param alarm
     * @param alarm_time
     * @return
     */
    bool SetAlarmPara(uint16_t alert,uint16_t alarm,uint16_t alarm_time);

    /**
     * @brief 抓图
     * @return
     */
    bool GetPicture();
    /**
     * @brief 获取实时温度
     * @return
     */
    bool GetRealTimeTemperature();
    /**
     * @brief 长连接启动
     * @return
     */
    bool KeepConnect();
    /**
     * @brief 长连接断开
     * @return
     */
    bool KeepDisconnect();
    /**
     * @brief 长连接重连
     * @return
     */
    bool KeepReconnect();
    /**
     * @brief 长连接状态
     * @return
     */
    NetState KeepState();

signals:

    /**
     * @brief 温度告警信号
     * @param temp
     */
    void sigTempAlarm(float temp);
    /**
     * @brief 接收到抓图数据
     * @param d
     */
    void sigCapPicture(QByteArray & d);
    /**
     * @brief 接收实时温度数据
     * @param d
     */
    void sigGetTemperature(QByteArray & d);
    /**
     * @brief 长连接中断告警
     */
    void sigKeepBrokeAlarm();

private slots:

    /**
     * @brief 长连接接收信息处理
     */
    void onKeepRelyfinished();
    /**
     * @brief 抓图接收信息处理
     */
    void onCapPicRelyfinished();
    /**
     * @brief 实时温度接受处理
     */
    void onGetTemperatureRelyfinished();
    /**
     * @brief 长连接定时器处理
     */
    void onKeepTimerOverProcess();

    /**
     * @brief 长连接超时处理
     */
    void onKeepConnectTimeOut();
    void onKeepConnectFinished(QNetworkReply *reply);

private:

    /**
     * @brief 阻塞put发送数据
     * @param url
     * @param bytes
     * @return
     */
    bool putWait(QString url, QByteArray& bytes);

    QNetworkAccessManager *m_pManager;
    QNetworkReply *keep;
    QTimer *keepTimer;  //长连接短线检测定时器，默认11秒超时

    uint32_t connect_over_time_seconds = 15000;

private:

    QString ip;
    QByteArray capPicData;
    QByteArray responseData;
    std::atomic<NetState> keepNetState;

    /**
     * @brief 长连接接收数据成功处理
     */
    void keepRelayOkProcess(QNetworkReply *reply);
    /**
     * @brief 长连接接收错误处理
     */
    void keepRelayErrProcess(QNetworkReply *reply);
};

#endif // MYNETMANAGER_H
