#include <Controller/MapController/MapController.hpp>
#include <Display/Display.hpp>
#include <Item/IEquipment.hpp>
#include <Widget/Builder/Builder.hpp>
#include <Widget/Label/Label.hpp>
#include <Widget/Layout/Center/Center.hpp>
#include <Widget/Layout/CompoundWidget/MapMenu/MapMenu.hpp>
#include <World/World.hpp>
#include <Display/WidgetDisplay/WorldDisplay/WorldDisplay.hpp>
#include <memory>

MapController::MapController(ControllerChannel &channel) :
    Controller(channel),
    remoteMap(this)
{}

void MapController::onConnect(IEquipment::MapLevel level)
{
    remoteMap.init(level);
}

Widget* MapController::getWidget()
{
    return new Builder<IEquipment::MapLevel>(
        [this]() { return remoteMap.getMapLevel(); },
        [this](IEquipment::MapLevel level) -> Widget*
        {
            if (level == IEquipment::MapLevel::None)
            {
                return new Center(new Label("Loading map..."));
            }

            auto worldDisplay = std::dynamic_pointer_cast<WorldDisplay>(Display::getCurrent());
            if (worldDisplay == nullptr)
            {
                crash("Failed to get the WorldDisplay in MapController::getWidget()");
            }

            return new MapMenu(
                *worldDisplay,
                level,
                remoteMap
            );
        }
    );
}

bool MapController::isBusy()
{
    return Widget::popup != nullptr;
}

void MapController::update()
{
    Controller::update();

    if (world.isLocal())
    {
        remoteMap.update();
    }
}