#include <Display.h>
#include <SSD1306Wire.h>

Display::Display(int sda, int scl, int readerid)
{
    this->readerid = readerid;
    display = new SSD1306Wire(0x3c, sda, scl);
    display->init();
    display->setTextAlignment(TEXT_ALIGN_CENTER);
    display->flipScreenVertically();

    ReaderInfo[0] = '\0';      // Empty string
    strcpy(Title, "Boot ..."); // Set initial title
    Info[0] = '\0';            // Empty string
}

void Display::clearReaderInfo()
{
    char buffer[DISPLAY_BUFFER_SIZE];
    sprintf(buffer, "%05d", readerid);
    writeReaderInfo(buffer);
}

void Display::createReaderInfo(const char *state)
{
    if (strlen(state) < DISPLAY_BUFFER_SIZE - 1 - 6)
    {
        char buffer[DISPLAY_BUFFER_SIZE];
        sprintf(buffer, "%s %05d", state, readerid);
        writeReaderInfo(buffer);
    }
}

void Display::writeReaderInfo(const char *text)
{
    if (strlen(text) < DISPLAY_BUFFER_SIZE - 1)
    {
        strcpy(ReaderInfo, text);
    }
    updateDisplay();
}

void Display::writeTitle(const char *text)
{
    if (strlen(text) < DISPLAY_BUFFER_SIZE - 1)
    {
        strcpy(Title, text);
    }
    updateDisplay();
}

void Display::writeInfo(const char *text)
{
    if (strlen(text) < DISPLAY_BUFFER_SIZE - 1)
    {
        strcpy(Info, text);
    }

    updateDisplay();
}

void Display::updateDisplay()
{
    display->clear();

    display->setFont(ArialMT_Plain_10);
    display->drawString(64, 0, ReaderInfo);

    display->setFont(ArialMT_Plain_24);
    display->drawString(64, 13, Title);

    display->setFont(ArialMT_Plain_16);
    display->drawString(64, 40, Info);

    display->display();
}

void Display::updateByMQTT(const char *topic, byte *payload, unsigned int length)
{
    char topic_displayTitle[] = "fabreader/00000/display/title";
    sprintf(topic_displayTitle, "fabreader/%05d/display/title", readerid);

    char topic_displayInfo[] = "fabreader/00000/display/info";
    sprintf(topic_displayInfo, "fabreader/%05d/display/info", readerid);

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

    char *buffer = new char[length + 1];
    memcpy(buffer, payload, length);

    if (!strcmp(topic, topic_displayTitle))
    {
        writeTitle(buffer);
    }
    else if (!strcmp(topic, topic_displayInfo))
    {
        writeInfo(buffer);
    }
    else if (!strcmp(topic, topic_stopOTA))
    {
        clearReaderInfo();
    }
}