#include <Sound/Sound.hpp>
#include <Widget/Layout/Column/Column.hpp>
#include <Widget/ColorSelector/ColorSelector.hpp>
#include <Widget/Layout/Row/Row.hpp>
#include <Widget/Slider/Slider.hpp>

void ColorSelector::activate()
{
    auto onSliderChanged = [this]()
    {
        onChanged();
    };

    Sound::select.play();
    openPopup(
        glm::ivec2(0, m_size.y),
        new Column(
            new Slider<uint8_t, int>(color.red, 0, 255, "Red: $+", onSliderChanged),
            new Slider<uint8_t, int>(color.green, 0, 255, "Green: $+", onSliderChanged),
            new Slider<uint8_t, int>(color.blue, 0, 255, "Blue: $+", onSliderChanged)
        )
    );
}

ColorSelector::ColorSelector(RGBABytes &bytes) : color(bytes) {}

ColorSelector* ColorSelector::withChangedCallback(ChangedCallback callback)
{
    onChanged = callback;
    return this;
}

glm::ivec2 ColorSelector::getMinSize()
{
    return glm::ivec2(buttonWidth, buttonHeight);
}

void ColorSelector::draw(GraphicsContext &context)
{
    color.alpha = 0xFF;

    glm::vec4 targetBackground = (isMouseInside() || isFocused() || isHostingPopup()) ?
        glm::vec4(1.0f) :
        Color::widgetBackground;
    context.color = backgroundLerp.sample(targetBackground);
    context.drawRect(0, 0, m_size.x, m_size.y);

    context.color = color.toNormalizedVec();
    context.drawRect(buttonMargin, buttonMargin, m_size.x - 2 * buttonMargin, m_size.y - 2 * buttonMargin);
}

void ColorSelector::onKeyDown(SDL_Keycode keycode)
{
    if (keycode == SDLK_SPACE || keycode == SDLK_RETURN)
    {
        activate();
    }
}

void ColorSelector::onMouseDown(Uint8 button)
{
    Widget::onMouseDown(button);
    if (isMouseInside())
    {
        activate();
    }
}

void ColorSelector::getInternalTabOrder(std::vector<Widget*> &tabOrder)
{
    tabOrder.push_back(this);
}