#include "MapWindow.h"

#include <TextFeld.h>

#include "Globals.h"

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

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

void MapWindow::setVisibility(bool visible)
{
    if ((visible && !map) || (!visible && map))
    {
        uiFactory.initParam.bildschirm->postAction([this, visible]() {
            if (visible && !map)
            {
                lockZeichnung();
                map = new DimensionMap(options);
                map->setSize(getInnenBreite(), getInnenHeight());
                addMember(map);
                unlockZeichnung();
                addStyle(Fenster::Style::Sichtbar);
            }
            if (!visible && map)
            {
                removeStyle(Fenster::Style::Sichtbar);
                lockZeichnung();
                removeMember(map);
                map = 0;
                unlockZeichnung();
            }
        });
    }
}

void MapWindow::addChunk(ChunkMap* chunk)
{
    lockZeichnung();
    if (map)
    {
        map->addChunk(chunk);
    }
    else
    {
        chunk->release();
    }
    unlockZeichnung();
}

void MapWindow::updatePlayerData(char* data)
{
    lockZeichnung();
    if (map) map->updatePlayers(data);
    unlockZeichnung();
}

bool MapWindow::tick(double time)
{
    if (map) map->setSize(getInnenBreite(), getInnenHeight());
    return OptionsWindow::tick(time);
}