#include <Controller/InventoryController/MiningRigController/MiningRigController.hpp>
#include <Machine/MMiningRig/MMiningRig.hpp>
#include <Widget/Builder/Builder.hpp>
#include <Widget/Label/Label.hpp>
#include <Widget/Layout/CompoundWidget/FormSection/FormSection.hpp>
#include <Widget/StaticItemSlot/ItemSlot/ItemSlot.hpp>
#include <Widget/Layout/Row/Row.hpp>
#include <Widget/Layout/Column/Column.hpp>
#include <Widget/Layout/Center/Center.hpp>
#include <memory>

MiningRigController::MiningRigController(ControllerChannel &channel) :
    InventoryController(channel),
    updateStats(this, RunsOn::Client,
        [this](MMiningRig::Stats stats) -> uint32_t
    {
        this->stats = stats;
        return 0;
    })
{}

void MiningRigController::onConnect(std::shared_ptr<Machine> miningRigMachine)
{
    miningRig = std::dynamic_pointer_cast<MMiningRig>(miningRigMachine);
    bindMachine(miningRigMachine);
}

Widget* MiningRigController::getRightPanel()
{
    return new Column(
        new Center(new Label("Mining rig")),

        new Row(
            makeItemSlotColumn("machine", 0, 5),
            makeItemSlotColumn("machine", 5, 5),
            makeItemSlotColumn("machine", 10, 5),
            makeItemSlotColumn("machine", 15, 5),
            makeItemSlotColumn("machine", 20, 5),
            makeItemSlotColumn("machine", 25, 5)
        ),

        new FormSection(
            new Column(
                new Builder<int>(
                    stats.depth,
                    [](int depth) -> Widget*
                    {
                        return new Label(formatString("Depth: $+", depth));
                    }
                ),
                new Builder<int>(
                    stats.blocksMined,
                    [](int blocksMined) -> Widget*
                    {
                        return new Label(formatString("Total blocks mined: $+", blocksMined));
                    }
                )
            )
        )
    );
}

void MiningRigController::update()
{
    InventoryController::update();

    if (world.isLocal() && miningRig != nullptr)
    {
        if (stats != miningRig->stats)
        {
            stats = miningRig->stats;
            updateStats(stats);
        }
    }
}