/*Copyright (C) 2010-2020 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 "TextButton.hpp"

TextButton::TextButton(const SkinBox &skin, const SkinSound &sounds) :
Button(skin, sounds)
{
    
}

TextButton::TextButton(const std::string &text, const SkinBox &skin, const SkinSound &sounds) :
Button(skin, sounds)
{
    setText(text);
}

void TextButton::draw()
{
    //Update matrix
    Drawable::pushMatrix();
    Drawable::updateMatrix();
    
    if (m_selected) m_selectedBack.draw();
    else if (m_focused) m_focusedBack.draw();
    else m_inactiveBack.draw();
    
    m_textField.draw();
    
    Drawable::popMatrix();
}

void TextButton::setFocus(bool focused)
{
    if (m_focused != focused)
    {
        Button::setFocus(focused);
        centerText();
    }
}

void TextButton::setSkin(const SkinBox &skin)
{
    Button::setSkin(skin);
    centerText();
}

void TextButton::centerText()
{
    float skinWidth = getWidth(), textWidth = m_textField.getWidth(),
          skinHeight = getHeight(), textHeight = m_textField.getHeight();
    
    if (skinWidth <= 0 || textWidth <= 0)
        return;
    
    // Text is overflowing horizontally
    if (textWidth > skinWidth)
        m_textField.setScale( (skinWidth / textWidth)*0.95 );
    else
        m_textField.setScale(1.f);
    
    // Center text
    float textScale = m_textField.getXScale();
    
    m_textField.setXPosition((skinWidth - textWidth*textScale) / 2);
    m_textField.setYPosition((skinHeight - textHeight*textScale) / 2);
}

void TextButton::setText(const std::string &text)
{
    m_textField.setText(text);
    centerText();
}

const std::string &TextButton::getText() const
{
    return m_textField.getText();
}

void TextButton::setTextFont(Font &textFont)
{
    m_textField.setFont(textFont);
    centerText();
}

const Font *TextButton::getTextFont() const
{
    return m_textField.getFont();
}

void TextButton::setTextColor(const Color &textColor)
{
    m_textField.setColor(textColor);
}

const Color &TextButton::getTextColor() const
{
    return m_textField.getColor();
}
