#include "MapWindow.h"

#include <TextField.h>

#include "Globals.h"

MapWindow::MapWindow()
    : OptionsWindow([this]() { options->addStyle(Window::Style::Visible); }),
      map(0)
{
    setTitel("Map");
    setClosingMe([this](void* p, void* o, Framework::MouseEvent me) {
        if (me.id == Framework::ME_RLeft)
        {
            setVisibility(0);
        }
        return 1;
    });
    setSize(500, 500);
    setPosition(uiFactory.initParam.bildschirm->getBackBufferSize().x / 2
                    - getWidth() / 2,
        uiFactory.initParam.bildschirm->getBackBufferSize().y / 2
            - getHeight() / 2);
    setBodyMin(200, 200);
    options = new MapOptions();
    options->getThis(); // increase reference counter outside of dynamic_cast to
                        // avoid compiler warning
    uiFactory.initParam.bildschirm->addMember(dynamic_cast<Drawable*>(options));
}

MapWindow::~MapWindow()
{
    options->release();
}

void MapWindow::setVisibility(bool visible)
{
    if ((visible && !map) || (!visible && map))
    {
        uiFactory.initParam.bildschirm->postAction([this, visible]() {
            if (visible && !map)
            {
                writeLock().lock();
                map = new DimensionMap(options);
                map->setSize(getInnerWidth(), getInnerHeight());
                addMember(map);
                writeLock().unlock();
                addStyle(Window::Style::Visible);
            }
            if (!visible && map)
            {
                removeStyle(Window::Style::Visible);
                writeLock().lock();
                removeMember(map);
                map = 0;
                writeLock().unlock();
            }
        });
    }
}

void MapWindow::addChunk(ChunkMap* chunk)
{
    writeLock().lock();
    if (map)
    {
        map->addChunk(chunk);
    }
    else
    {
        chunk->release();
    }
    writeLock().unlock();
}

void MapWindow::updatePlayerData(char* data)
{
    readLock().lock();
    if (map) map->updatePlayers(data);
    readLock().unlock();
}

bool MapWindow::tick(double time)
{
    readLock().lock();
    if (map) map->setSize(getInnerWidth(), getInnerHeight());
    readLock().unlock();
    return OptionsWindow::tick(time);
}