#include "PopupMenu.h"

MenuItem::MenuItem(const wchar_t* caption)
: Label(0, true), _subMenu(0)
{
    setCaption(caption);

    connectEvent(Event::MOUSE_ENTER, this, (EventHandler)&MenuItem::onMouseEnter);
    connectEvent(Event::MOUSE_LEAVE, this, (EventHandler)&MenuItem::onMouseLeave);
}

MenuItem::~MenuItem()
{
}

void MenuItem::setSize(Size& size)
{
    Window::setSize(size);

    _caption->setPosition(Vector3(37.0f / _size.w(), 0.0f, 0.0f));
    _caption->setScale(Vector3((_size.w() - 37.0f) / _size.w(), 1.0f, 0.0f));
    _caption->setMaxWidth(_size.w() - 37.0f);
    _caption->setMaxHeight(_size.h());

    if (_subMenu != 0) {
        _subMenu->setPosition(Point(_size.w(), 0.0f));
    }
}

PopupMenu* MenuItem::getSubMenu()
{
    return _subMenu;
}

void MenuItem::setSubMenu(PopupMenu* subMenu)
{
    _subMenu = subMenu;

    if (_subMenu != 0) {
        _subMenu->setParent(this);
        _subMenu->setPosition(Point(_size.w(), 0.0f));
    }
}

void MenuItem::onMouseEnter(Event& event)
{
    if (_subMenu != 0)
        _subMenu->setVisible(true);
}

void MenuItem::onMouseLeave(Event& event)
{
    if (_subMenu != 0) {
        if (_subMenu->isHit(event.mouseX, event.mouseY) == false)
            _subMenu->setVisible(false);
    }
}



class PopupMenu::SideStrip : public Window {
public:
    SideStrip(Window* parent);
    virtual ~SideStrip();
};

PopupMenu::SideStrip::SideStrip(Window* parent)
: Window(parent)
{
    setPosition(Point(0.0f, 0.0f));
    setSize(Size(32.0f, 0.0f));

    _texture = ResourceManager::instance().loadTexture(L"textures/gui/menu_sidestrip.dds");
}

PopupMenu::SideStrip::~SideStrip()
{
}

PopupMenu::PopupMenu(Window* parent)
: Window(parent), _sideStrip(0), _maxWidth(0.0f)
{
    setPosition(Point(0.0f, 0.0f));
    setSize(Size(132.0f, 0.0f));

    _texture = ResourceManager::instance().loadTexture(L"textures/default.dds");

    _sideStrip = new SideStrip(this);

    setVisible(false);
}

PopupMenu::~PopupMenu()
{
    delete _sideStrip;
}

void PopupMenu::addItem(MenuItem* item)
{
    setSize(Size(132.0f, (_items.size() + 1) * 24.0f));
    _sideStrip->setSize(Size(32.0f, _size.h()));

    item->setParent(this);

    item->setPosition(Point(0.0f, _items.size() * 24.0f));
    item->setSize(Size(132.0f, 24.0f));

    _items.push_back(item);
}