import { world, system, BlockPermutation } from "@minecraft/server"
import { ModalFormData } from "@minecraft/server-ui"


export class RedstoneLooperComponent {
    constructor() {
        this.onTick = this.onTick.bind(this);
        this.onPlayerInteract = this.onPlayerInteract.bind(this);

        this.DYNAMIC_PROPERTY_NAME = "pb_red:redstone_counter_data";
        this.REDSTONE_POWER_BLOCKS = [
            { id: "minecraft:redstone_wire", state: "redstone_signal" },
            { id: "minecraft:powered_repeater", state: "minecraft:cardinal_direction" },
            { id: "minecraft:unpowered_repeater", state: "minecraft:cardinal_direction" }
        ];
        this.maxCount = 0;
        this.countReach = false
    }

    getFrontandBack(direction, block) {
        let frontBlock;
        switch (direction) {
            case 'north':
                frontBlock = block.north();
                break;
            case 'south':
                frontBlock = block.south();
                break;
            case 'east':
                frontBlock = block.east();
                break;
            case 'west':
                frontBlock = block.west();
                break;
        }
        return { frontBlock };
    }

    onPlayerInteract(e) {
        const block = e.block;
        const player = e.player;

        let selectedSlot = player.selectedSlotIndex;
        let handItem = player.getComponent("inventory").container.getItem(selectedSlot);
        if (handItem?.typeId == "pb_red:redstone_wrench") {
            const AllStates = [
                { state: "minecraft:cardinal_direction", values: ["north", "east", "south", "west"] },
                { state: "minecraft:facing_direction", values: ["north", "east", "south", "west", "up", "down"] }
            ]

            AllStates.some((stateObj) => {
                const currentState = block.permutation.getState(stateObj.state);

                if (currentState !== undefined && currentState !== null) {
                    const stateValues = stateObj.values;
                    const currentStateIndex = stateValues.indexOf(currentState);
                    const nextState = currentStateIndex >= stateValues.length - 1 ? stateValues[0] : stateValues[currentStateIndex + 1];

                    block.setPermutation(block.permutation.withState(stateObj.state, nextState));
                    block.dimension.runCommand(`playsound vr.stutterturn @a ${block.location.x} ${block.location.y} ${block.location.z}`)
                }
            });
            return;
        }

        let loopInterval = block.permutation.getState('pb_red:loop_interval');
        if (loopInterval < 5) {
            block.setPermutation(block.permutation.withState('pb_red:loop_interval', loopInterval + 1));
            block.dimension.runCommand(`playsound random.click @a ${block.location.x} ${block.location.y} ${block.location.z}`)
        }
        else {
            block.setPermutation(block.permutation.withState('pb_red:loop_interval', 1));
            block.dimension.runCommand(`playsound random.click @a ${block.location.x} ${block.location.y} ${block.location.z}`)
        }
    }

    onTick(e) {
        const { block } = e;
        let direction = block.permutation.getState('minecraft:cardinal_direction');
        const { frontBlock } = this.getFrontandBack(direction, block);
        const directionList = ["north", "east", "south", "west"];
        if (!frontBlock) return
        if (frontBlock.permutation.matches("minecraft:unpowered_repeater") && frontBlock.permutation.getState("minecraft:cardinal_direction") === directionList[(directionList.indexOf(direction) - 2 + directionList.length) % directionList.length]) {
            frontBlock.setPermutation(BlockPermutation.resolve("minecraft:powered_repeater", { 'minecraft:cardinal_direction': directionList[(directionList.indexOf(direction) - 2 + directionList.length) % directionList.length] }));
            system.runTimeout(() => {
                try {
                    if (frontBlock)
                        frontBlock.setPermutation(BlockPermutation.resolve("minecraft:unpowered_repeater", { 'minecraft:cardinal_direction': directionList[(directionList.indexOf(direction) - 2 + directionList.length) % directionList.length] }));
                } catch {
                    //  console.warn("Unloaded chunck error (redstone Looper)")
                }
            }, 2)
        }
        block.setPermutation(block.permutation.withState('pb_red:powered_out', true));
        system.runTimeout(() => {
            try {
                if (!block.isAir)
                    block.setPermutation(block.permutation.withState('pb_red:powered_out', false));
            } catch {
                //  console.warn("Unloaded chunck error (redstone Looper)")
            }
        }, 2)


    }
}
