

export class ItemFilterComponent {
    constructor() {
        this.onStepOn = this.onStepOn.bind(this);
        this.onPlayerInteract = this.onPlayerInteract.bind(this);

        this.FILTER_ITEM_LIST = []
        this.impulseVector = { x: 0, y: 0, z: 0 };
    }
    onPlayerInteract(e) {
        //console.warn("interact")
        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;
        }

        block.dimension.runCommand(`playsound vr.stutterturn @a ${block.location.x} ${block.location.y} ${block.location.z}`)
        if (block.permutation.getState('pb_red:inversed') == true) {
            block.setPermutation(block.permutation.withState('pb_red:inversed', false))
        } else {
            block.setPermutation(block.permutation.withState('pb_red:inversed', true))
        }
    }

    getFrontandBack(direction, block) {
        let frontOffset, leftOffset;
        switch (direction) {
            case 'north':
                frontOffset = { x: 0, y: 0, z: -1 }
                leftOffset = { x: -1, y: 0, z: 0 }
                break;
            case 'south':
                frontOffset = { x: 0, y: 0, z: 1 }
                leftOffset = { x: 1, y: 0, z: 0 }
                break;
            case 'east':
                frontOffset = { x: 1, y: 0, z: 0 }
                leftOffset = { x: 0, y: 0, z: -1 }
                break;
            case 'west':
                frontOffset = { x: -1, y: 0, z: 0 }
                leftOffset = { x: 0, y: 0, z: 1 }
                break;
        }
        return { frontOffset, leftOffset }
    }
    onStepOn(e) {
        const block = e.block
        let direction = block.permutation.getState('minecraft:cardinal_direction')
        let { frontOffset, leftOffset } = this.getFrontandBack(direction, block)
        for (const aboveEntity of block.dimension.getEntitiesAtBlockLocation(block.location)) {
            if (aboveEntity.typeId == 'minecraft:player') {
                return
            }
            let entityLoc = aboveEntity.location
            //aboveEntity.getComponent('minecraft:movement')?.setCurrentValue(0)
            const blockCenterX = block.location.x + 0.5;
            const blockCenterZ = block.location.z + 0.5;
            // If the direction is along the x-axis, center on the z-axis
            if (Math.abs(frontOffset.x) > Math.abs(frontOffset.z)) {
                if (entityLoc.z > blockCenterZ + 0.1)
                    aboveEntity.teleport({ x: entityLoc.x, y: entityLoc.y + 0.05, z: blockCenterZ })
                else if (entityLoc.z < blockCenterZ - 0.1)
                    aboveEntity.teleport({ x: entityLoc.x, y: entityLoc.y + 0.05, z: blockCenterZ })
            }
            // If the direction is along the z-axis, center on the x-axis
            else {
                if (entityLoc.x > blockCenterX + 0.1)
                    aboveEntity.teleport({ x: blockCenterX, y: entityLoc.y + 0.05, z: entityLoc.z })
                else if (entityLoc.x < blockCenterX - 0.1)
                    aboveEntity.teleport({ x: blockCenterX, y: entityLoc.y + 0.05, z: entityLoc.z })
            }
            // aboveEntity.setRotation({ x: 0, y: rotation })
            aboveEntity.clearVelocity()

            this.impulseVector = { x: frontOffset.x / 3, y: frontOffset.y + 0.05, z: frontOffset.z / 3 }

            const container = block.above()
            if (aboveEntity.typeId == "minecraft:item" && this.isValidContainer(container)) {
                this.FILTER_ITEM_LIST = []

                let inventory = container?.getComponent("minecraft:inventory")?.container;
                if (!inventory) return;
                for (let slot = 0; slot < inventory.size; slot++) {
                    let chestItem = inventory.getItem(slot);
                    if (chestItem) {
                        this.FILTER_ITEM_LIST.push({
                            typeId: chestItem.typeId,
                            nameTag: chestItem.nameTag || null // Use null if nameTag is undefined
                        });
                    }
                }

                let itemStack = aboveEntity.getComponent('minecraft:item').itemStack;
                let itemId = itemStack.typeId;
                let itemNameTag = itemStack.nameTag || null; // Use null if nameTag is undefined

                // Function to check if an item matches the filter criteria
                function isItemInFilter(itemId, itemNameTag) {
                    return this.FILTER_ITEM_LIST.some(filterItem =>
                        filterItem.typeId === itemId &&
                        filterItem.nameTag === itemNameTag
                    );
                }

                if (block.permutation.getState('pb_red:inversed') === true) {
                    if (isItemInFilter.call(this, itemId, itemNameTag)) {
                        aboveEntity.clearVelocity();
                        this.impulseVector = { x: leftOffset.x / 2, y: leftOffset.y + 0.05, z: leftOffset.z / 2 };
                    }
                } else {
                    if (!isItemInFilter.call(this, itemId, itemNameTag)) {
                        aboveEntity.clearVelocity();
                        this.impulseVector = { x: leftOffset.x / 2, y: leftOffset.y + 0.05, z: leftOffset.z / 2 };
                    }
                }
            }
            aboveEntity.applyImpulse(this.impulseVector)
        }
    }

    isValidContainer(block) {
        if (!block) return;
        const validContainers = [
            "minecraft:chest",
            "minecraft:hopper",
            "minecraft:barrel",
            "minecraft:dropper",
            "minecraft:dispenser",
            "minecraft:trapped_chest",
            //shulker box
            "minecraft:undyed_shulker_box",
            "minecraft:black_shulker_box",
            "minecraft:blue_shulker_box",
            "minecraft:brown_shulker_box",
            "minecraft:cyan_shulker_box",
            "minecraft:gray_shulker_box",
            "minecraft:green_shulker_box",
            "minecraft:light_blue_shulker_box",
            "minecraft:light_gray_shulker_box",
            "minecraft:lime_shulker_box",
            "minecraft:magenta_shulker_box",
            "minecraft:orange_shulker_box",
            "minecraft:pink_shulker_box",
            "minecraft:purple_shulker_box",
            "minecraft:red_shulker_box",
            "minecraft:white_shulker_box",
            "minecraft:yellow_shulker_box",


        ];
        return validContainers.includes(block.typeId);
    }
}