#include <Controller/GadgetController/GadgetController.hpp>
#include <Controller/GadgetController/MinimapController/MinimapController.hpp>
#include <Display/WidgetDisplay/WorldDisplay/WorldDisplay.hpp>
#include <Item/StatelessItem/BasicItem/NavItem/NavItem.hpp>
#include <MapTool/MapTool.hpp>
#include <RemoteMap/RemoteMap.hpp>
#include <Widget/Label/Label.hpp>
#include <Widget/Layout/Column/Column.hpp>
#include <Widget/Layout/Margin/Margin.hpp>
#include <Widget/Layout/Row/Row.hpp>
#include <Widget/Panel/Panel.hpp>
#include <MapTool/MapPanTool/MapPanTool.hpp>
#include <Display/Display.hpp>

MinimapController::MinimapController(ControllerChannel &channel) :
    GadgetController(channel),
    remoteMap(this)
{}

void MinimapController::update()
{
    if (world.isLocal())
    {
        remoteMap.update();
    }
}

void MinimapController::initLocal(const ItemStack &stack)
{
    auto nav = stack.getItemAs<NavItem>();
    if (nav == nullptr)
    {
        Log::error(formatString("Attempted to open the minimap with non-nav item: $+", stack.getItem()->name));
        return;
    }

    remoteMap.init(nav->getMapLevel());
}

Widget* MinimapController::getWidget()
{
    auto worldDisplay = std::dynamic_pointer_cast<WorldDisplay>(Display::getCurrent());
    static MapTool *tool = &MapPanTool::instance;

    return new Row(
        Layout::WithProportion<1>(),
        new Panel(),
        
        new Column(
            new Margin<5, 5, 0, 0>(
                (new MapView(
                    *worldDisplay,
                    remoteMap,
                    *player,
                    tool
                ))->withPlayerTracking()
            )
        )
    );
}