import * as mc from "@minecraft/server";

const particle_coordinates = [
    { x: 1.5 * 1 / 16, y: 0.82, z: -5.5 * 1 / 16 },
    { x: 5.5 * 1 / 16, y: 0.82, z: -2.5 * 1 / 16 },

    { x: 5.5 * 1 / 16, y: 0.82, z: 1.5 * 1 / 16 },
    { x: 2.5 * 1 / 16, y: 0.82, z: 5.5 * 1 / 16 },

    { x: -1.5 * 1 / 16, y: 0.82, z: 5.5 * 1 / 16 },
    { x: -5.5 * 1 / 16, y: 0.82, z: 2.5 * 1 / 16 },

    { x: -5.5 * 1 / 16, y: 0.82, z: -1.5 * 1 / 16 },
    { x: -2.5 * 1 / 16, y: 0.82, z: -5.5 * 1 / 16 }
]

export class lightablemManager {
    static interact(data) {
        const block = data.block;
        const player = data.player;
        const location = block.location;

        try {
            //if cake has been eaten from, lights off!
            if (block.permutation.getState("sgs_cake:sections") > 0) {
                block.setPermutation(block.permutation.withState('sgs_cake:lit', 0));
                return;
            }

            const lit = data.block.permutation.getState("sgs_cake:lit");
            if (lit == 0) {
                const mainhand = player.getComponent(mc.EntityEquippableComponent.componentId).getEquipmentSlot(mc.EquipmentSlot.Mainhand);
                const heldItem = mainhand.getItem();
                if (heldItem == undefined) return;

                if (heldItem.typeId == "minecraft:flint_and_steel") {
                    block.dimension.playSound("fire.ignite", location);
                    block.setPermutation(block.permutation.withState('sgs_cake:lit', 1));
                    this.playParticles(block);
                }
            }
            else {
                block.setPermutation(block.permutation.withState('sgs_cake:lit', 0));
            }
        } catch (error) {

        }
    }

    static tick(data) {
        if (data.block.permutation.getState("sgs_cake:lit") == 0) return;
        this.playParticles(data.block);
    }

    static playParticles(block) {
        const location = block.bottomCenter();
        const dimension = block.dimension;
        const cardinal = block.permutation.getState("minecraft:cardinal_direction");

        particle_coordinates.forEach(element => {
            const target_location = { x: location.x + element.x, y: location.y + element.y, z: location.z + element.z }
            mc.world.getDimension(dimension.id).spawnParticle("minecraft:candle_flame_particle", target_location);
        });
    }
}
