#include "WindowManager.h"

#include "DesktopManager.h"

WindowManager::WindowManager(DesktopManager* desktopManager)
    : mWindows(),
      mDesktopManager(desktopManager)
{
    addWindow(mt::Window::Create(mDrawMode, desktopManager->getFontsManager()));
}

WindowManager::~WindowManager()
{

}

std::unique_ptr<WindowManager> WindowManager::Create(DesktopManager* desktopManager)
{
    return std::make_unique<WindowManager>(desktopManager);
}

void WindowManager::onPaintEvent(const PaintEvent* event)
{
    getMainWindow()->onPaint(event);
}

void WindowManager::onMouseEvent(const MouseEvent* event)
{
    getMainWindow()->onMouseEvent(event);
}

void WindowManager::onResizeEvent(const ResizeEvent* event)
{
    getMainWindow()->setSize(event->getWidth(), event->getHeight());
}

void WindowManager::onKeyboardEvent(const KeyboardEvent* event)
{
    getMainWindow()->onKeyboardEvent(event);
}

void WindowManager::addWindow(WindowUPtr window)
{
    auto popup_handler = [this](mt::Window* parent, std::unique_ptr<Widget> popup){
        onAddPopupWindow(parent, std::move(popup));
    };
    window->setPopupHandler(popup_handler);
    mWindows.push_back(std::move(window));
}

void WindowManager::onAddPopupWindow(mt::Window* parent, std::unique_ptr<Widget> widget)
{
    auto popup = mt::Window::Create(mDrawMode, mDesktopManager->getFontsManager());
    popup->setWidget(std::move(widget));
    popup->setParent(parent);

    auto popup_raw = popup.get();
    addWindow(std::move(popup));

    mDesktopManager->addWindow(popup_raw);
}

void WindowManager::clearPlatformWindows()
{
    for (auto& window : mWindows)
    {
        window->clearPlatformWindow();
    }
}

mt::Window* WindowManager::getMainWindow() const
{
    if(mWindows.size()>0)
    {
        return mWindows[0].get();
    }
    else
    {
        return nullptr;
    }
}

void WindowManager::onLoopIteration(mt::Screen* screen)
{
    for (auto& window : mWindows)
    {
        if (window->isDirty())
        {
            window->onPaint(nullptr);
            window->doPaint(screen);
        }
    }
}
