#include <Settings/Settings.hpp>
#include <Widget/ScancodePicker/ScancodePicker.hpp>

ScancodePicker::ScancodePicker(const std::string &action) : action(action) {}

void ScancodePicker::draw(GraphicsContext &context)
{
    int offsetY = 0;
    if (isMouseInside())
    {
        offsetY = height;
    }

    if (isFocused())
    {
        offsetY = 2 * height;
    }

    context.color = glm::vec4(1.0f);
    context.drawMaterial(
        Material::scancodePicker,
        0, offsetY, width, height,
        0, 0, width, height
    );

    std::string label;
    std::optional<SDL_Scancode> scancode = settings.keyBindings.getScancodeForAction(action);

    if (scancode.has_value())
    {
        label = SDL_GetKeyName(SDL_GetKeyFromScancode(*scancode, 0, true));
    }

    const int textWidth = context.measureText(Font::generic, label).x;
    context.drawText(Font::generic, (m_size.x - textWidth) / 2, 2, label);
}

glm::ivec2 ScancodePicker::getMinSize()
{
    return glm::ivec2(width, height);
}

void ScancodePicker::onKeyUp(SDL_Keycode keycode)
{
    if (keycode != SDLK_ESCAPE)
    {
        SDL_Scancode scancode = SDL_GetScancodeFromKey(keycode, nullptr);
        settings.keyBindings.setActionScancode(action, scancode);
        settings.save();
    }

    Widget::focused = nullptr;
}