#include <Controller/GadgetController/GadgetController.hpp>
#include <Controller/GadgetController/JetpackController/JetpackController.hpp>
#include <Item/StatefulItem/Jetpack/Jetpack.hpp>
#include <ItemStack/ItemStack.hpp>
#include <Widget/FluidLevelIndicator/FluidLevelIndicator.hpp>
#include <Widget/IconLabel/IconLabel.hpp>
#include <Widget/Layout/Center/Center.hpp>
#include <Widget/Layout/Column/Column.hpp>
#include <Widget/Layout/CompoundWidget/Deck/Deck.hpp>
#include <Widget/Layout/Frame/Frame.hpp>
#include <Widget/Layout/Margin/Margin.hpp>
#include <Widget/Layout/Row/Row.hpp>
#include <Widget/Panel/Panel.hpp>
#include <World/World.hpp>
#include <cstdint>

JetpackController::JetpackController(ControllerChannel &channel) :
    GadgetController(channel),
    updateJetpack(this, RunsOn::Client,
        [this](std::string fluidName, uint32_t amount) -> uint32_t
    {
        this->fluidName = fluidName;
        this->amount = amount;

        return 0;
    })
{}

void JetpackController::update()
{
    if (world.isLocal())
    {
        const ItemStack &stack = getBoundStack();
        const auto jetpack = stack.getItemAs<Jetpack>();

        if (fluidName != jetpack->getFluidName(stack) || amount != jetpack->getFluidAmount(stack))
        {
            fluidName = jetpack->getFluidName(stack);
            amount = jetpack->getFluidAmount(stack);

            updateJetpack(fluidName, amount);
        }
    }
}

Widget* JetpackController::getWidget()
{
    return new Column(
        Layout::WithProportion<1>(),
        new Panel(),

        new Row(
            new Margin<0, 0, 5, 40>(
                new Frame(
                    Color::gadgetBackground,
                    new Deck<Row, Center>(
                        new IconLabel(Material::jetpack),
                        new Panel(glm::ivec2(2, 0)),
                        new FluidLevelIndicator(
                            fluidName,
                            amount,
                            Jetpack::capacity
                        )
                    )
                )
            )
        )
    );
}