#include <Block/SpriteBlock/EngineeringTable/EngineeringTable.hpp>
#include <Entity/PhysicsEntity/CameraEntity/Player/Player.hpp>
#include <Milestone/ElectronicsMilestone/ElectronicsMilestone.hpp>
#include <World/LocalWorld/LocalWorld.hpp>
#include <Controller/InventoryController/EngineeringTableController/EngineeringTableController.hpp>

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

    for (uint8_t meta = 0; meta < 4; meta++)
    {
        Side inputSide(meta);
        Sprite sprite = {
            {
                "engineeringTable/side",
                "engineeringTable/side",
                "engineeringTable/side",
                "engineeringTable/side",
                "engineeringTable/bottom",
                "engineeringTable/top"
            },
            {{0, 0, 0, 8, 8, 8}},
            formatString("input$+", inputSide),
        };

        sprite.texturesOnSides[inputSide.asNumber()] = "engineeringTable/electricInput";

        sprites.push_back(sprite);
    }

    return sprites;
}

EngineeringTable::EngineeringTable(std::string name) :
    SpriteBlock(
        name,
        "Engineering Table",
        90.0f,
        "engineeringTable/top",
        makeSprites()
    )
{
    withMetalSounds();
}

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

void EngineeringTable::onInteract(LocalWorld &world, Player &player, glm::ivec3 pos, Side side, const RGBABytes &collisionKey)
{
    if (player.isHoldingScrewdriver())
    {
        uint8_t meta = *world.getBlockMeta(pos);
        uint8_t newDir = (meta & 3) + 1;
        uint8_t newRest = meta & ~3;
        world.setBlockMeta(pos, (newDir & 3) | newRest, true);

        return;
    }

    player.achieve(ElectronicsMilestone::ID, ElectronicsMilestone::EngineeringTable);
    player.connectController<EngineeringTableController>(
        "main:EngineeringTableController",
        world.getMachine(pos)
    );
}

void EngineeringTable::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)
    {
        int i;
        for (i=0; i<inv->getNumSlots(); i++)
        {
            ItemStack stack = inv->getStackInSlot(i);
            if (!stack.isEmpty())
            {
                stacks.push_back(stack);
            }
        }
    }
}

Sound& EngineeringTable::getBackgroundSound(uint8_t meta)
{
    if (meta & metaActive)
    {
        return Sound::construct;
    }

    return Sound::NONE;
}

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