#ifndef __CDCUPDATER_H__
#define __CDCUPDATER_H__

#include <QObject>
#include <QSerialPortInfo>
#include <optional>

class QSerialPort;

class CdcUpdater : public QObject {
    Q_OBJECT
public:
    enum Command : uint8_t {
        EnterUpgrade = 0xF1,
        EnterUpgradeReply = 0xF2,

        TransferBin = 0xF3,
        TransferBinReply = 0xF4,

        ExitUpgrade = 0xF5,
        ExitUpgradeReply = 0xF6,

        GetVersion = 0xF7,
        GetVersionReply = 0xF8,

        CurrentVersion = 0xF9, // 设备上报
        CurrentVersionReply = 0xFA,

        StartUpgrade = 0xFB,
        StartUpgradeReply = 0xFC,

        Md5ChecksumReply = 0xEB,
        Md5Checksum = 0xEC,

        UpgradeExit = 0xE9, // 模组推出boot时回复
    };
    CdcUpdater(QObject *parent = nullptr);
    ~CdcUpdater();
    void start(const QString &path, const QSerialPortInfo &info = QSerialPortInfo());
    void startSearchDevice();
    bool open(const QSerialPortInfo &info);
    static std::optional<QSerialPortInfo> searchDevice();

signals:
    void deviceDiscovered(const QSerialPortInfo &info);
    void updateFinished();
    void progressChanged(int32_t progress);
    void message(const QString &text);

protected:
    bool write(Command command, const uint8_t *data = nullptr, uint32_t size = 0);
    void timerEvent(QTimerEvent *event) final;
    void transferBin();
    void onReadyRead();

private:
    std::shared_ptr<QSerialPort> m_serialPort;
    int m_timerId = -1;
    std::string m_path;
    std::shared_ptr<std::ifstream> m_ifs;
    int m_totalPackageSize = -1;
    int m_packetIndex = 0;
    int32_t m_progress = 0;
    int32_t m_progressBeforeTranster = 0; // 用于内部进度表示
};
#endif // __CDCUPDATER_H__
