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


export class RedstoneCounterComponent {
    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.countReach = false
    }

    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 };
    }
    getCounterData() {
        return JSON.parse(world.getDynamicProperty(this.DYNAMIC_PROPERTY_NAME) || "[]");
    }

    setCounterData(data) {
        world.setDynamicProperty(this.DYNAMIC_PROPERTY_NAME, JSON.stringify(data));
    }

    updateCounterData(block, delta) {
        const locationStr = `${block.location.x},${block.location.y},${block.location.z}`;
        let data = this.getCounterData();
        let counter = data.find(counter => counter.loc === locationStr);

        if (!counter) {
            counter = { loc: locationStr, currentCount: 0, maxCount: 10 };
            data.push(counter);
        }

        if (counter.currentCount + delta < counter.maxCount) {
            counter.currentCount += delta
            const progressionBar = Math.ceil((counter.currentCount / counter.maxCount) * 10)
            block.setPermutation(block.permutation.withState('pb_red:current_count_progression', progressionBar));
        } else {
            this.countReach = true
            counter.currentCount += delta
            const progressionBar = Math.ceil((counter.currentCount / counter.maxCount) * 10)
            //  console.warn(progressionBar)
            block.setPermutation(block.permutation.withState('pb_red:current_count_progression', progressionBar));
            counter.currentCount = 0
            system.runTimeout(() => {
                try {
                    block.setPermutation(block.permutation.withState('pb_red:current_count_progression', 0));
                } catch { }
            }, 10)
        }

        this.setCounterData(data);
    }

    transformNumberTo1to10(number, originalMin, originalMax) {
        const normalized = (number - originalMin) / (originalMax - originalMin);
        const transformed = normalized * (10 - 1) + 1;
        return Math.round(transformed);
    }

    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;
        }

        this.updateCounterData(block, 0)

        const locationStr = `${block.location.x},${block.location.y},${block.location.z}`;
        let data = this.getCounterData();
        let counter = data.find(counter => counter.loc === locationStr);
        block.dimension.runCommand(`playsound random.click @a ${block.location.x} ${block.location.y} ${block.location.z}`)

        const RedstoneCounterGUI = new ModalFormData()
        RedstoneCounterGUI.title("Redstone Counter")
        RedstoneCounterGUI.slider("Count to reach", 1, 100, 1, counter.maxCount ? counter.maxCount : 10)
        RedstoneCounterGUI.show(player).then((selec) => {
            if (selec.canceled) {
                return;
            }
            counter.maxCount = selec.formValues[0];
            counter.currentCount = 0;
            this.setCounterData(data);
        });
    }

    removeDynamicProperties(block) {
        const locationStr = `${block.location.x},${block.location.y},${block.location.z}`;
        let data = this.getCounterData();
        data = data.filter(counter => counter.loc !== locationStr);
        this.setCounterData(data);
    }

    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:powered_in', false));
            block.setPermutation(block.permutation.withState('pb_red:powered_out', false));
            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:powered_in') == true;
        if (hasRedstonePower && !previousState) {
            this.updateCounterData(block, 1);

            block.setPermutation(block.permutation.withState('pb_red:powered_in', true));
            if (this.countReach) {
                this.countReach = false
                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] }));
                }
                block.setPermutation(block.permutation.withState('pb_red:powered_out', true));
            }
        } else if ((!hasRedstonePower) && previousState) {
            block.setPermutation(block.permutation.withState('pb_red:powered_in', false));
            block.setPermutation(block.permutation.withState('pb_red:powered_out', false));
        }
    }
}
