// Import necessary modules from Minecraft server API
import { world, BlockPermutation, BlockTypes } from '@minecraft/server';

// Helper: determine cardinal direction by player rotation
function getNewCardinalDirection(currentDirection, angle) {
    const direction = directionDisplay(angle);
    if (['north', 'south'].includes(currentDirection)) {
        return direction.includes('south') ? 'south' : 'north';
    } else {
        return direction.includes('west') ? 'west' : 'east';
    }
}

function directionDisplay(angle) {
    if (Math.abs(angle) > 112.5) return 'north';
    if (Math.abs(angle) < 67.5) return 'south';
    if (angle < 157.5 && angle > 22.5) return 'west';
    if (angle > -157.5 && angle < -22.5) return 'east';
    return '';
}


// Register the custom component
world.beforeEvents.worldInitialize.subscribe(eventData => {
    eventData.blockComponentRegistry.registerCustomComponent('pu_biomes:fence_gate', {

        onPlayerInteract(e) {
            const { block, player, face } = e;
            const equipment = player.getComponent('equippable');
            const selectedItem = equipment.getEquipment('Mainhand');
        
            // Place block above if interacting upwards with an item
            if (selectedItem && face === 'Up' && BlockTypes.get(selectedItem.typeId)) {
                const aboveBlock = block.above();
                if (aboveBlock.typeId === 'pu_biomes:fence_gate') {
                    aboveBlock.setType(selectedItem.typeId);
                    if (player.getGameMode() !== "creative") {
                        if (selectedItem.amount > 1) {
                            selectedItem.amount -= 1;
                            equipment.setEquipment('Mainhand', selectedItem);
                        } else {
                            equipment.setEquipment('Mainhand', undefined);
                        }
                    }
                    return;
                }
            }
        
            // Toggle open/close and rotate
            const currentState = block.permutation.getState('pu_biomes:open');
            const newOpenState = !currentState;
            const sound = newOpenState ? 'open.fence_gate' : 'close.fence_gate';
        
            const rotationAngle = player.getRotation().y;
            const currentDirection = block.permutation.getState('minecraft:cardinal_direction');
            const newCardinalDirection = getNewCardinalDirection(currentDirection, rotationAngle);
        
            const newPermutation = BlockPermutation.resolve(block.typeId, {
                ...block.permutation.getAllStates(),
                'pu_biomes:open': newOpenState,
                'minecraft:cardinal_direction': newCardinalDirection
            });
        
            block.setPermutation(newPermutation);
            block.dimension.playSound(sound, block.location);   
        }        
    });
});