#include "StatusIcons.h"

static statusIcon_t * icons[MAX_STATUS_ICONS];
static uint8_t visibleOnFrame[32];

// Kresleni indikacnich ikon (bezici wifi, nezname zarizeni na siti, ...)
void SIdraw(OLEDDisplay *display, OLEDDisplayUiState *state)
{
    bool on = false;

    if (state->frameState != FIXED)
        return;

    for (size_t i = 0; i < sizeof(visibleOnFrame); i++)
        if (visibleOnFrame[i] == state->currentFrame) {
            on = true;
            break;
        }
    if (on) {
        // overlay ikony pracuji jen na povolenych ramcich
        int iconsCount = 0;
        int visible = ui.blinkIsVisible();
        uint16_t xiconpos = display->getWidth() / 2;

        display->setColor(WHITE);
        for (int i = 0; i < MAX_STATUS_ICONS; i++) {
            if (nullptr != icons[i]) {
                if (0xff == icons[i]->xPos) {
                    xiconpos -= icons[i]->xSize / 2;
                    ++iconsCount;
                } else if ((0 == icons[i]->blink) || visible) {
                    display->drawXbm(icons[i]->xPos, icons[i]->yPos, icons[i]->xSize, icons[i]->ySize, icons[i]->xbmData);
                }
            }
        }
        if (iconsCount) {
            for (int i = 0; i < MAX_STATUS_ICONS; i++)
                if (nullptr != icons[i]) {
                    if (0xff == icons[i]->xPos) {
                        if ((0 == icons[i]->blink) || visible) {
                            display->drawXbm(xiconpos, display->getHeight() - 1 - icons[i]->ySize, icons[i]->xSize, icons[i]->ySize, icons[i]->xbmData);
                        }
                        xiconpos += icons[i]->xSize;
                    }
                }
        }
    }
}

StatusIcons::StatusIcons()
{

    for (int i = 0; i < MAX_STATUS_ICONS; i++)
        icons[i] = nullptr;
    for (size_t i = 0; i < sizeof(visibleOnFrame); i++)
        visibleOnFrame[i] = 0xff;
}

void StatusIcons::add(const statusIcon_t *ptr)
{
    int idx = -1;

    for (int i = 0; i < MAX_STATUS_ICONS; i++) {
        if ((-1 == idx) && (nullptr == icons[i]))
            idx = i;
        if (icons[i] == ptr)
            return; // ikona uz na displeji je
    }
    if (-1 != idx)
        icons[idx] = (statusIcon_t *)ptr;
}

void StatusIcons::remove(const statusIcon_t *ptr)
{

    for (int i = 0; i < MAX_STATUS_ICONS; i++)
        if (icons[i] == ptr)
            icons[i] = nullptr;
}

void StatusIcons::addVisibleFrameId(uint8_t id)
{

    for (size_t i = 0; i < sizeof(visibleOnFrame); i++) {
        if (visibleOnFrame[i] == id)
            return; // uz je aktivovane
        if (visibleOnFrame[i] == 0xff) {
            visibleOnFrame[i] = id;
            return;
        }
    }
}

StatusIcons si;
