#include "Button.h"

Button::Button(Window* parent, bool toggle)
: Window(parent), _toggleButton(toggle), _toggled(false), _state(NORMAL), _normalTexture(0), _highlightedTexture(0), _depressedTexture(0)
{
    setPosition(Point(0.0f, 0.0f));
    setSize(Size(80.0f, 24.0f));

    _normalTexture = ResourceManager::instance().loadTexture(L"textures/gui/button.dds");
    _highlightedTexture = ResourceManager::instance().loadTexture(L"textures/gui/button_highlighted.dds");
    _depressedTexture = ResourceManager::instance().loadTexture(L"textures/gui/button_depressed.dds");
    _disabledTexture = ResourceManager::instance().loadTexture(L"textures/gui/button_disabled.dds");

    _texture = _normalTexture;

    connectEvent(Event::MOUSE_ENTER,      this, (EventHandler)&Button::onMouseEnter);
    connectEvent(Event::MOUSE_LEAVE,      this, (EventHandler)&Button::onMouseLeave);
    connectEvent(Event::MOUSE_LEFT_DOWN,  this, (EventHandler)&Button::onMouseLeftDown);
    connectEvent(Event::MOUSE_LEFT_CLICK, this, (EventHandler)&Button::onMouseLeftClick);
}

Button::~Button()
{

}

bool Button::isToggleButton()
{
    return _toggleButton;
}

void Button::setToggleButton(bool toggle)
{
    _toggleButton = toggle;
}

bool Button::isToggled()
{
    return _toggled;
}

void Button::toggle(bool toggled)
{
    _toggled = toggled;

    if (_toggled) {
        _state = DEPRESSED;
        _texture = _depressedTexture;
    }
    else {
        _state = NORMAL;
        _texture = _normalTexture;
    }
}

void Button::enable(bool enabled)
{
    Window::enable(enabled);
    
    if (!_enabled)
        _texture = _disabledTexture;
    else
        _texture = _normalTexture;
}

void Button::onMouseEnter(Event& event)
{
    if (_enabled) {
        if ((!_toggleButton) || (_toggleButton && (!_toggled))) {
            _state = HIGHLIGHTED;
            _texture = _highlightedTexture; 
        }
    }
}

void Button::onMouseLeave(Event& event)
{
    if (_enabled) {
        if ((!_toggleButton) || (_toggleButton && (!_toggled))) {
            _state = NORMAL;
            _texture = _normalTexture; 
        }
    }
}

void Button::onMouseLeftDown(Event& event)
{
    if (_enabled) {
        _state = DEPRESSED;
        _texture = _depressedTexture;
    }
}

void Button::onMouseLeftClick(Event& event)
{
    if (_enabled) {
        _toggled = !_toggled;
       
        if (_toggleButton && _toggled) {
            _state = DEPRESSED;
            _texture = _depressedTexture;
        }
        else {
            _state = HIGHLIGHTED;
            _texture = _highlightedTexture;
        }
    }
}
