#include "otaproxy.h"
#include "nfc.h"
#include <PubSubClient.h>

OTAProxy::OTAProxy(PubSubClient *mqttClient, NFC *nfc, int id)
{
    this->mqtt = mqttClient;
    this->nfc = nfc;
    this->id = id;
}

bool OTAProxy::hasActiveOTA()
{
    return activeOTA;
}

void OTAProxy::startOTA()
{
    if (!(nfc->hasCardSelected()))
    {
        return;
    }
    activeOTA = true;

    char topic[] = "fabreader/00000/startOTA";
    sprintf(topic, "fabreader/%05d/startOTA", id);
    MFRC522::Uid uid = nfc->getUID();
    mqtt->publish(topic, uid.uidByte, uid.size);

    Serial.println("Start OTA");
}

void OTAProxy::continueOTA(char *topic, byte *payload, unsigned int length)
{
    char topic_requestOTA[] = "fabreader/00000/requestOTA";
    sprintf(topic_requestOTA, "fabreader/%05d/requestOTA", id);

    char topic_responseOTA[] = "fabreader/00000/responseOTA";
    sprintf(topic_responseOTA, "fabreader/%05d/responseOTA", id);

    char topic_stopOTA[] = "fabreader/00000/stopOTA";
    sprintf(topic_stopOTA, "fabreader/%05d/stopOTA", id);

    char topic_restartOTA[] = "fabreader/00000/restartOTA";
    sprintf(topic_restartOTA, "fabreader/%05d/restartOTA", id);

    if (!strcmp(topic, topic_requestOTA))
    {
        Serial.println("Request OTA");
        byte response[APDU_BUFFER_SIZE] = {0};
        byte response_len;

        MFRC522::StatusCode status;

        Serial.println("Run Transceive");
        status = nfc->Transceive(payload, length, response, &response_len);
        Serial.printf("PICC_Tranceive: 0x%02x\n", status);

        if (status != MFRC522::STATUS_OK)
        {
            cancelOTA();
            return;
        }

        mqtt->publish(topic_responseOTA, response, response_len);
        Serial.println("Response OTA");
    }
    else if (!strcmp(topic, topic_stopOTA))
    {
        Serial.println("Stop OTA");
        nfc->disconnectCard();
        activeOTA = false;
    }
    // else if(!strcmp(topic, topic_restartOTA))
    // {
    //     Serial.println("Restart OTA");
    //     while(!(nfc->deselectCard()));
    //     // if(nfc->hasNewCard())
    //     // {
    //     //     startOTA();
    //     // }
    // }
}

void OTAProxy::cancelOTA()
{
    char topic_cancelOTA[] = "fabreader/00000/cancelOTA";
    sprintf(topic_cancelOTA, "fabreader/%05d/cancelOTA", id);
    MFRC522::Uid uid = nfc->getUID();
    mqtt->publish(topic_cancelOTA, uid.uidByte, uid.size);

    while (!(nfc->disconnectCard()))
        ;
    activeOTA = false;

    Serial.println("Cancel OTA");
}