#include <Block/SpriteBlock/QuartzClock/QuartzClock.hpp>
#include <Entity/PhysicsEntity/CameraEntity/Player/Player.hpp>
#include <World/LocalWorld/LocalWorld.hpp>
#include <Controller/InventoryController/QuartzClockController/QuartzClockController.hpp>

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

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

        sprite.texturesOnSides[outputSide.asNumber()] = "quartzClock/dataOutput";

        sprites.push_back(sprite);
    }

    return sprites;
}

QuartzClock::QuartzClock(std::string name) :
    SpriteBlock(
        name,
        "Quartz Clock",
        90.0f,
        "quartzClock/top",
        makeSprites()
    )
{
    withMetalSounds();
}

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

void QuartzClock::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.connectController<QuartzClockController>(
        "main:QuartzClockController",
        world.getMachine(pos)
    );
}

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