#include "OledMenuDriver.h"
#include "OledMenuPaint.h"
#include "../2025_include_user/OledMenuConfig.h"

const MenuPaint::Menu *MenuPaint::currentMenu = nullptr;
uint8_t MenuPaint::currentMenuSize = 0;
int8_t MenuPaint::selectIndex = 0;
int8_t MenuPaint::scrollOffset = 0;
bool MenuPaint::switchStates[20] = {0};
const MenuPaint::Menu *MenuPaint::menuStack[5] = {nullptr};
uint8_t MenuPaint::stackIndex = 0;

void MenuPaint::Init() {
    currentMenu = menuRoot;
    currentMenuSize = sizeof(menuRoot) / sizeof(Menu);
    selectIndex = 0;
    scrollOffset = 0;
}

void MenuPaint::Paint() {
    MenuDriver::canvasClear();

    for (int i = 0; i < 4; i++) {
        int itemIndex = scrollOffset + i;
        if (itemIndex >= currentMenuSize) break;

        const Menu &item = currentMenu[itemIndex];

        bool selected = (itemIndex == selectIndex);
        bool checked = false;

        if (item.type == MENU_TYPE_SWITCH) {
            checked = switchStates[item.switchId];
        }

        RenderItem(16 * i, item.name, selected, checked);
    }

    MenuDriver::canvasUpdate();
}

void MenuPaint::RenderItem(int y, const char *text, bool selected, bool checked) {
    MenuDriver::drawChinese(0, y + 12, text);

    if (selected) {
        MenuDriver::drawFrame(0, y, 128, 16);
    }

    if (checked) {
        MenuDriver::drawCheckMark(128 - 12, y + 2, 10, 10);
    }
}

void MenuPaint::ScrollUp() {
    if (selectIndex > 0) {
        selectIndex--;
        if (selectIndex < scrollOffset) scrollOffset--;
        Paint();
    }
}

void MenuPaint::ScrollDown() {
    if (selectIndex < currentMenuSize - 1) {
        selectIndex++;
        if (selectIndex >= scrollOffset + 4) scrollOffset++;
        Paint();
    }
}

void MenuPaint::Enter() {
    const Menu &item = currentMenu[selectIndex];
    if (item.type == MENU_TYPE_FOLDER && item.subMenus != nullptr) {
        if (stackIndex < 5) {
            menuStack[stackIndex++] = currentMenu;
        }
        currentMenu = item.subMenus;
        currentMenuSize = item.subMenuCount;
        selectIndex = 0;
        scrollOffset = 0;
        Paint();
    } else if (item.type == MENU_TYPE_SWITCH) {
        if (item.switchId < sizeof(switchStates)) {
            switchStates[item.switchId] = !switchStates[item.switchId];
        }
        Paint();
    }
}

void MenuPaint::Exit() {
    if (stackIndex > 0) {
        currentMenu = menuStack[--stackIndex];
        currentMenuSize = sizeof(menuRoot) / sizeof(Menu);  // 示例只返回一级
        selectIndex = 0;
        scrollOffset = 0;
        Paint();
    }
}

bool MenuPaint::GetSwitchState(uint8_t switchId) {
    if (switchId >= sizeof(switchStates)) return false;
    return switchStates[switchId];
}
