


export class ItemMagnetComponent {
    constructor() {
        this.onTick = this.onTick.bind(this);
        this.impulseVector = { x: 0, y: 0, z: 0 };
        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;
        this.tickCpt = 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.block;
        let direction = block.permutation.getState('minecraft:cardinal_direction');
        const { frontBlock, backBlock, leftBlock, rightBlock } = this.getFrontandBack(direction, block);
        const directionList = ["north", "east", "south", "west"];

        let redstonePower = 0;
        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', false));
            return false;
        }
        const { id, state } = redstoneBlock;
        if (id === "minecraft:redstone_wire") {
            redstonePower = backBlock.permutation.getState(state);

        } else {
            if (id === "minecraft:powered_repeater") {
                if (backBlock.permutation.getState(state) === directionList[(directionList.indexOf(direction) - 2 + directionList.length) % directionList.length])
                    redstonePower = 15
            }
        }
        const radius = redstonePower;

        if (radius <= 0) {
            block.setPermutation(block.permutation.withState('pb_red:powered', false));
            return;
        }
        block.setPermutation(block.permutation.withState('pb_red:powered', true));

        const centerX = block.location.x + 0.5;
        const centerY = block.location.y + 0.5;
        const centerZ = block.location.z + 0.5;
        const center = { x: centerX, y: centerY, z: centerZ }

        const entities = block.dimension.getEntities({
            location: block.location,
            maxDistance: radius,
            type: 'minecraft:item'
        });
        block.setPermutation(block.permutation.withState('pb_red:magnet', false));
        for (const entity of entities) {
            block.setPermutation(block.permutation.withState('pb_red:magnet', true));

            const dx = centerX - entity.location.x;
            const dy = centerY - entity.location.y;
            const dz = centerZ - entity.location.z;

            const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
            if (distance > 1) {
                let force = 0
                if (distance > 2)
                    force = 1 / distance;
                else
                    force = distance * 0.1;
                this.impulseVector.x = (dx / distance) * force;
                this.impulseVector.y = (dy / distance) * force;
                this.impulseVector.z = (dz / distance) * force;
                entity.applyImpulse(this.impulseVector);
                block.dimension.spawnParticle("pb_red:magnet_active", { x: centerX, y: centerY, z: centerZ });
                this.tickCpt++
                if (this.tickCpt % 21 == 0) {
                    block.dimension.runCommand(`playsound pb_red.magnet_loop @a ${block.location.x} ${block.location.y} ${block.location.z} 0.2`)
                }
            }

        }
    }
    generateParticlesBetweenPositions(pos1, pos2, distance, particleType, block) {
        const numParticles = Math.max(1, Math.round((distance / 15) * 30));

        for (let i = 0; i <= numParticles; i++) {
            const t = i / numParticles;
            const particleX = pos1.x + (pos2.x - pos1.x) * t;
            const particleY = pos1.y + (pos2.y - pos1.y) * t;
            const particleZ = pos1.z + (pos2.z - pos1.z) * t;

            block.dimension.spawnParticle(particleType, { x: particleX, y: particleY, z: particleZ });
        }
    }
}


