#include "enternumber.h"
#include <fonts/DejaVu_sans_mono_bold_14.h>

static String entertext;
static uint8_t maxDigits; // pocet zadavanych cislic
static uint8_t decplaces; // pocet desetinnych mist
static uint8_t digits[8]; // hodnota v cislicich (nastavovana polozka)
static uint8_t digitIdx; // index menene cifry
static bool done; // priznak, ze bylo zadani dokoncene

void dialog_prepareEnterNumber(String message, int oldNumber, uint8_t numbers, uint8_t decimals)
{

    entertext = message;
    maxDigits = numbers;
    decplaces = decimals;
// naplnime cislice
    int i = numbers - 1;
    while (i >= 0) {
        digits[i] = oldNumber % 10;
        oldNumber /= 10;
        i--;
    }
    digitIdx = 0; // nastavujeme od prvni cifry
    done = false;
    ui.goToFrame(ui.getFrameIndex(drawEnterNumber)); // aktivujeme zadavani cisla
}

#define NCHARWIDTH 10
// Menu, ktere dovoli zadat cislo o potrebnem poctu cislic
void drawEnterNumber(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y)
{

    display->setTextAlignment(TEXT_ALIGN_CENTER);
    display->setFont(DejaVu_Sans_Mono_Bold_14);
    display->setColor(WHITE);
    display->drawString(64 + x, 8 + y, entertext);
// TODO:
    int16_t xpos = 64 - ((maxDigits / 2) * NCHARWIDTH);
    for (int i = 0; i < maxDigits; i++) {
        if (digitIdx == i) {
            if (ui.blinkIsVisible())
                display->drawString(xpos + x, 32 + y, String(digits[i]));
        } else
            display->drawString(xpos + x, 32 + y, String(digits[i]));
        xpos += NCHARWIDTH;
    }

    if (state->frameState == FIXED) {
        uint8_t key = ui.handleKbd();
        switch (key) {
        case KEY_DOWN:
            digits[digitIdx]++;
            digits[digitIdx] %= 10;
            break;

        case KEY_UP:
            digits[digitIdx]--;
            if (digits[digitIdx] > 9)
                digits[digitIdx] = 9;
            break;

        case KEY_ENTER:
            digitIdx++;
            if (digitIdx == maxDigits) {
                done = true; // mame ukoncene zadani noveho cisla
                ui.goToPrevFrame();
            }
            break;

        case KEY_EXIT:
            ui.goToPrevFrame();
            break;
        }
    }
}

int32_t dialog_getEnterNumberResult(void)
{
    int32_t num = 0;
    uint8_t i = 0;

    while (i < maxDigits) {
        num *= 10;
        num += digits[i];
        i++;
    }
    return num;
}

bool dialog_getEnterNumberDone(void)
{
    bool result = done;

    done = false;
    return result;
}
