#include <Block/SpriteBlock/OilRefinery/OilRefinery.hpp>
#include <Milestone/FossilFuelsMilestone/FossilFuelsMilestone.hpp>
#include <World/LocalWorld/LocalWorld.hpp>
#include <Entity/PhysicsEntity/CameraEntity/Player/Player.hpp>
#include <Controller/InventoryController/OilRefineryController/OilRefineryController.hpp>

std::vector<OilRefinery::Sprite> OilRefinery::makeSprites()
{
    std::vector<Sprite> sprites;

    for (uint8_t meta = 0; meta < 4; ++meta)
    {
        Side inputSide(meta);
        Side outputSide = inputSide.opposite();

        Sprite sprite = {
            {
                "oilRefinery/side",
                "oilRefinery/side",
                "oilRefinery/side",
                "oilRefinery/side",
                "oilRefinery/electricInput",
                "oilRefinery/top"
            },
            {{0, 0, 0, 8, 8, 8}},
            formatString("input$+", inputSide),
        };

        sprite.texturesOnSides[inputSide.asNumber()] = "oilRefinery/input";
        sprite.texturesOnSides[outputSide.asNumber()] = "oilRefinery/output";

        sprites.push_back(sprite);
    }

    return sprites;
}

OilRefinery::OilRefinery(std::string name) :
    SpriteBlock(
        name,
        "Oil Refinery",
        30.0f,
        "oilRefinery/side",
        makeSprites()
    )
{
    withMetalSounds();
}

bool OilRefinery::canManuallyDig()
{
    return true;
}

void OilRefinery::onInteract(LocalWorld &world, Player &player, glm::ivec3 pos, Side side, const RGBABytes &collisionKey)
{
    if (player.isHoldingScrewdriver())
    {
        world.setBlockMeta(pos, (*world.getBlockMeta(pos) + 1) % 4, true);
        return;
    }

    player.achieve(FossilFuelsMilestone::ID, FossilFuelsMilestone::OilRefinery);
    player.connectController<OilRefineryController>(
        "main:OilRefineryController",
        world.getMachine(pos)
    );
}

void OilRefinery::getHarvestedStacks(LocalWorld &world, glm::ivec3 pos, std::vector<ItemStack> &stacks)
{
    SpriteBlock::getHarvestedStacks(world, pos, stacks);

    std::shared_ptr<IInventory> inv = std::dynamic_pointer_cast<IInventory>(world.getMachine(pos));
    if (inv != nullptr)
    {
        for (int i = 0; i < inv->getNumSlots(); i++)
        {
            ItemStack stack = inv->getStackInSlot(i);
            if (!stack.isEmpty())
            {
                stacks.push_back(stack);
            }
        }
    }
}

bool OilRefinery::canPlace(LocalWorld &world, IWorldActor &actor, glm::ivec3 pos, Side side, uint8_t &meta)
{
    meta = actor.getSideFacing2D().opposite().asNumber();
    return true;
}