#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()
{
    nfc->selectCard();
    activeOTA = true;

    char topic[] = "fabreader/00000/startOTA";
    sprintf(topic, "fabreader/%05d/startOTA", id);
    mqtt->publish(topic, "");
}

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);

    if(strcmp(topic, topic_requestOTA))
    {
        byte response[APDU_BUFFER_SIZE] = {0};
        nfc->Transceive(payload, length, response, APDU_BUFFER_SIZE);

        mqtt->publish(topic_responseOTA, response, APDU_BUFFER_SIZE);
    }

    if(strcmp(topic, topic_stopOTA))
    {
        nfc->deselectCard();
        activeOTA = false;
    }
}

void OTAProxy::cancelOTA()
{
    char topic_cancelOTA[] = "fabreader/00000/cancelOTA";
    sprintf(topic_cancelOTA, "fabreader/%05d/cancelOTA", id);
    mqtt->publish(topic_cancelOTA, "");

    nfc->deselectCard();
    activeOTA = false;
}