//
// Created by sasha on 27.11.2025.
//

#include "recordscreen.h"

#include "engine/engine.h"
#include "engine/widgets/image.h"
#include "engine/widgets/text.h"
#include "record_store.h"
#include "audio_effect.h"
#include "engine/tools/Profiler.h"
#include "engine/locale.h"

RecordScreen::RecordScreen() : IScreen("records") {
    SDL_Log("=> RecordScreen::RecordScreen");

    curType="easy";

    Locale *locale = Locale::getInstance();

    this->setBackgroundColor(0x57,0x74,0xD9);

    auto button_back = new Image(this,16,34,57,32,"button_back_blue.png");
    button_back->setCallback(CallbackType::EVENT_FINGER_UP,[]{
        AudioEffect::click();
        Engine::setActiveScreen("main");
    });

    auto text_records = new Text(this,16,115);
    text_records->setCached(true);
    text_records->setText(locale->tr("Records"),"inter.ttf",40,{255,255,255});

    auto label2 = new Text(this,16,text_records->getFRect().y+text_records->getFRect().h+5);
    label2->setCached(true);
    label2->setText(locale->tr("Top 5"),"inter.ttf",12,{0xD5,0xD5,0xD5});

    auto head = new Image(this,16,232,328,78,"record_head.png");

    selector = new RecordSelector(this,16,232);
    selector->onSelect([this](const std::string &type){
        AudioEffect::click();
        curType=type;
        refreshTable(type);
    });

    auto text_n = new Text(this,52.5, 346);
    text_n->setCached(true);
    text_n->setText("№","inter.ttf",20,{0xff,0xff,0xff});

    auto text_turn = new Text(this,146.5, 346);
    text_turn->setCached(true);
    text_turn->setText(locale->tr("Turns"),"inter.ttf",17,{0xff,0xff,0xff});

    auto text_time = new Text(this,253.5, 346);
    text_time->setCached(true);
    text_time->setText(locale->tr("Times"),"inter.ttf",17,{0xff,0xff,0xff});


    auto line = new Image(this,36,375,288,1,"record_line.png");

    for (int i=0;i<5;i++) {
        auto *rline = new RecordLine(this, 36, 382+i*(55+7), i==0);
        listLines.push_back(rline);
    }
}

void RecordScreen::refreshTable(const std::string &type) {
    RecordStore recordStore;
    std::vector<RECORD> records = recordStore.load(type);
    SDL_Log("records %s size: %zu",type.c_str(),records.size());

    for (int i=0;i<5;i++) {
        if (records.size()<=i){
            listLines.at(i)->hide();
            continue;
        }
        SDL_Log("rec %i %i",records.at(i).turn,records.at(i).time);

        listLines.at(i)->show();
        listLines.at(i)->setScore(i+1,records.at(i).turn,records.at(i).time);
    }
}

void RecordScreen::onActive(const VariantMap &args) {
    refreshTable(curType);
}

