/*Copyright (C) 2010-2023 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Hikou no mizu is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "Checkbox.hpp"
#include "Engines/Sound/SoundEngine.hpp"

Checkbox::Checkbox() : Checkbox(false, 20.f, 2.f) {}

Checkbox::Checkbox(bool checked, float boxSize, float borderSize) : Widget(),
m_checked(checked), m_size(boxSize), m_color(27, 66, 119),
m_soundEngine(nullptr)
{
    m_checkbox = Polygon::rectangle(m_size, m_size);
    m_checkbox.setBorderSize(borderSize);

    updateBox();
}

void Checkbox::draw()
{
    //Update matrix
    Drawable::pushMatrix();
    Drawable::updateMatrix();

    m_checkbox.draw();

    Drawable::popMatrix();
}

bool Checkbox::mouseRelease(const Vector &mouseCoords)
{
    if (Widget::contains(Widget::localCoords(mouseCoords)))
    {
        //Launch click sound
        if (m_soundEngine != nullptr && !m_clickSound.empty())
            m_soundEngine->playSound(m_clickSound);

        m_checked = !m_checked;
        updateBox();

        return true;
    }

    return false;
}

bool Checkbox::mouseClick(const Vector &mouseCoords)
{
    Vector localMouse = Widget::localCoords(mouseCoords);
    return Widget::contains(localMouse);
}

bool Checkbox::mouseMove(const Vector &mouseCoords)
{
    if (Widget::contains(Widget::localCoords(mouseCoords)))
    {
        setFocus(true);
        return true;
    }

    setFocus(false);
    return false;
}

void Checkbox::setFocus(bool focused)
{
    if (m_focused != focused)
    {
        Widget::setFocus(focused);

        //Update widget
        if (m_focused)
        {
            m_checkbox.setScale(1.1f);
            m_checkbox.setOrigin(m_size * .05f, m_size * .05f);
        }
        else
        {
            m_checkbox.setScale(1.f);
            m_checkbox.setOrigin(0.f, 0.f);
        }
    }
}

void Checkbox::check(bool checked)
{
    m_checked = checked;
    updateBox();
}

bool Checkbox::isChecked() const
{
    return m_checked;
}

void Checkbox::setSoundEngine(SoundEngine &soundEngine)
{
    m_soundEngine = &soundEngine;
}

void Checkbox::setClickSound(const std::string &clickSound)
{
    m_clickSound = clickSound;
}

float Checkbox::getWidth() const
{
    return m_size;
}

float Checkbox::getHeight() const
{
    return m_size;
}

void Checkbox::updateBox()
{
    m_checkbox.setUniformColor(m_checked ? m_color : Color(0, 0, 0, 0));
}
