import * as mc from "@minecraft/server";
import { highlightBlock, itemManager } from "../sgs_cake_lib";

const BLOCK_ENTITY = "sgs_cake:umbrella";
const COLORS = [
    {
        id: 0,
        name: "red"
    },
    {
        id: 1,
        name: "black"
    },
    {
        id: 2,
        name: "blue"
    },
    {
        id: 3,
        name: "brown"
    },
    {
        id: 4,
        name: "cyan"
    },
    {
        id: 5,
        name: "gray"
    },
    {
        id: 6,
        name: "green"
    },
    {
        id: 7,
        name: "light_blue"
    },
    {
        id: 8,
        name: "lime"
    },
    {
        id: 9,
        name: "magenta"
    },
    {
        id: 10,
        name: "orange"
    },
    {
        id: 11,
        name: "pink"
    },
    {
        id: 12,
        name: "purple"
    },
    {
        id: 13,
        name: "silver"
    },
    {
        id: 14,
        name: "white"
    },
    {
        id: 15,
        name: "yellow"
    }
]

export class umbrellaManager {

    static onplace(data, parameters) {
        const block = data.block;
        const location = block.bottomCenter();

        const color = parameters.params.color;
        const colordata = COLORS.find((f) => f.name == color);

        let canPlace = true;
        if (!block.above().isAir) canPlace = false;

        if (canPlace) {
            const display_entity = mc.world.getDimension(block.dimension.id).spawnEntity(BLOCK_ENTITY, location);

            display_entity.setProperty("sgs_cake:variant", colordata.id);
            highlightBlock(block);
            highlightBlock(block.above());
        }
        else {
            const loc = block.location;
            block.dimension.runCommand(`setblock ${loc.x} ${loc.y} ${loc.z} air [] destroy`);
        }
    }

    static interact(data, parameters) {
        const block = data.block;
        const location = block.bottomCenter();
        const display_entity = getDisplayEntity(block);

        const open = display_entity.getProperty("sgs_cake:open");
        if (open) {
            display_entity.setProperty("sgs_cake:open", false);
            block.dimension.playSound("random.pop", location);
        }
        else {
            display_entity.setProperty("sgs_cake:open", true);
            block.dimension.playSound("random.pop", location);
        }
    }

    static destroy(data, parameters) {
        const block = data.block;
        const display_entity = getDisplayEntity(block);
        display_entity.remove();
    }
}

export function getDisplayEntity(block) {
    const location = block.bottomCenter();
    return mc.world.getDimension(block.dimension.id).getEntities({ location, families: ["sgs_cake_umbrella"], maxDistance: 0.2 })[0];
}