#ifndef HOMEKIT_LIB_MQTT_MODULE_OTA_H
#define HOMEKIT_LIB_MQTT_MODULE_OTA_H

#include <stdint.h>
#include <Ticker.h>
#include <homekit/mqtt/module.h>

namespace homekit::mqtt {

enum class OtaResult: uint8_t {
    OK = 0,
    UPDATE_ERROR = 1,
    WRITE_ERROR = 2,
};

struct OtaStatus {
    uint16_t dataPacketId;
    uint16_t publishResultPacketId;
    bool finished;
    bool readyToRestart;
    size_t written;

    OtaStatus()
            : dataPacketId(0)
            , publishResultPacketId(0)
            , finished(false)
            , readyToRestart(false)
            , written(0)
    {}

    inline void clean() {
        dataPacketId = 0;
        publishResultPacketId = 0;
        finished = false;
        readyToRestart = false;
        written = 0;
    }

    inline bool started() const {
        return dataPacketId != 0;
    }
};

struct MqttOtaResponsePayload {
    OtaResult status;
    uint8_t error_code;
} __attribute__((packed));


class MqttOtaModule: public MqttModule {
private:
    OtaStatus ota;
    Ticker restartTimer;

    uint16_t sendResponse(Mqtt& mqtt, OtaResult status, uint8_t error_code = 0) const;

public:
    MqttOtaModule() : MqttModule(0, true, true) {}

    void init(Mqtt& mqtt) override;
    void tick(Mqtt& mqtt) override;
    void handlePayload(Mqtt& mqtt, String& topic, uint16_t packetId, const uint8_t *payload, size_t length, size_t index, size_t total) override;
    void handleOnPublish(uint16_t packetId) override;
    void handleOnDisconnect(espMqttClientTypes::DisconnectReason reason) override;
    inline bool isReadyToRestart() const {
        return ota.readyToRestart;
    }
};

}

#endif //HOMEKIT_LIB_MQTT_MODULE_OTA_H
