import { BlockPermutation } from "@minecraft/server"


export class RedstoneRandomizerComponent {
    constructor() {
        this.onTick = this.onTick.bind(this);
        this.onPlayerInteract = this.onPlayerInteract.bind(this);
        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.redstonePower = 0;
    }

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

        const player = e.player;
        let selectedSlot = player.selectedSlotIndex;
        let handItem = player.getComponent("inventory").container.getItem(selectedSlot);

        if (handItem) {
            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}`)
                    }
                });
            }
        }
    }

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

    onTick(e) {
        const { block } = e;
        let direction = block.permutation.getState('minecraft:cardinal_direction');
        const { frontBlock, backBlock, leftBlock, rightBlock } = this.getFrontandBack(direction, block);
        const directionList = ["north", "east", "south", "west"];
        let hasRedstonePower = false;
        if (!backBlock) return
        const redstoneBlock = this.REDSTONE_POWER_BLOCKS.find(({ id }) => backBlock.permutation.matches(id));
        if (!redstoneBlock) {
            block.setPermutation(block.permutation.withState('pb_red:turn_direction', 0));
            return false;
        }
        const { id, state } = redstoneBlock;
        if (id === "minecraft:redstone_wire") {
            let redstonePowerState = backBlock.permutation.getState(state);
            if (redstonePowerState > 0)
                hasRedstonePower = true;
        } else {
            if (id === "minecraft:powered_repeater") {
                if (backBlock.permutation.getState(state) === directionList[(directionList.indexOf(direction) - 2 + directionList.length) % directionList.length])
                    hasRedstonePower = true;
            }
        }

        const previousState = block.permutation.getState('pb_red:turn_direction') > 0;
        if (hasRedstonePower && !previousState) {
            switch (Math.floor(Math.random() * 3)) {
                case 0:
                    block.setPermutation(block.permutation.withState('pb_red:turn_direction', 1));
                    if (leftBlock.permutation.matches("minecraft:unpowered_repeater") && leftBlock.permutation.getState("minecraft:cardinal_direction") === directionList[(directionList.indexOf(direction) - 3 + directionList.length) % directionList.length]) {
                        leftBlock.setPermutation(BlockPermutation.resolve("minecraft:powered_repeater", { 'minecraft:cardinal_direction': directionList[(directionList.indexOf(direction) - 3 + directionList.length) % directionList.length] }));
                    }
                    break;
                case 1:
                    block.setPermutation(block.permutation.withState('pb_red:turn_direction', 2));
                    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] }));
                    }
                    break;
                case 2:
                    block.setPermutation(block.permutation.withState('pb_red:turn_direction', 3));
                    if (rightBlock.permutation.matches("minecraft:unpowered_repeater") && rightBlock.permutation.getState("minecraft:cardinal_direction") === directionList[(directionList.indexOf(direction) - 1 + directionList.length) % directionList.length]) {
                        rightBlock.setPermutation(BlockPermutation.resolve("minecraft:powered_repeater", { 'minecraft:cardinal_direction': directionList[(directionList.indexOf(direction) - 1 + directionList.length) % directionList.length] }));
                    }
                    break;
            }

        } else if ((!hasRedstonePower) && previousState) {
            block.setPermutation(block.permutation.withState('pb_red:turn_direction', 0));
        }
    }
}