import { world, BlockPermutation, ItemStack, GameMode, system } from '@minecraft/server';

world.afterEvents.itemStartUseOn.subscribe(eventData => {
    const player = eventData.source;
    const block = eventData.block;
    const equipment = player.getComponent('equippable');
    const selectedItem = equipment.getEquipment('Mainhand');

    if (!block.hasTag("WoodenStake"))return;

    const isLeashed = block.permutation.getState("r:leash");

    if(isLeashed)return;

    const hasCrop = block.permutation.getState("r:crop");

    if (selectedItem && selectedItem.typeId == 'rustic:rope' && !player.isSneaking && hasCrop == 'none'){
        eventData.cancel = true

        system.run( () => {
            block.setPermutation(block.permutation.withState("r:leash", true));
            if(block.north().hasTag("leashed")){
                block.north().setPermutation(block.north().permutation.withState("r:south", true));
                block.setPermutation(block.permutation.withState("r:north", true));
            }
            if(block.south().hasTag("leashed")){
                block.south().setPermutation(block.south().permutation.withState("r:north", true));
                block.setPermutation(block.permutation.withState("r:south", true));
            }
            if(block.east().hasTag("leashed")){
                block.east().setPermutation(block.east().permutation.withState("r:west", true));
                block.setPermutation(block.permutation.withState("r:east", true));
            }
            if(block.west().hasTag("leashed")){
                block.west().setPermutation(block.west().permutation.withState("r:east", true));
                block.setPermutation(block.permutation.withState("r:west", true));
            }
            player.dimension.runCommand(`playsound leashknot.place @a ${block.x} ${block.y} ${block.z}`)
            if (selectedItem.amount > 1) {
                if (player.getGameMode() !== "creative"){
                    selectedItem.amount -= 1;
                }
                equipment.setEquipment('Mainhand', selectedItem);
            } else if (selectedItem.amount === 1 && player.getGameMode() !== "creative") {
                equipment.setEquipment('Mainhand', undefined);
            }
        })
    }
    else if(selectedItem && selectedItem.typeId == 'rustic:chili_pepper_seeds' || selectedItem && selectedItem.typeId == 'rustic:tomato_seeds'){

        if(block.permutation.getState("r:crop") != "none") return;

        if(block.below().typeId != 'rustic:fertile_soil' && block.below().typeId != 'minecraft:farmland') return;

        const cropType = selectedItem.typeId == 'rustic:chili_pepper_seeds' ? "chili" : "tomato";

        system.run( () => {
            block.setPermutation(block.permutation.withState("r:crop", cropType));
            block.setPermutation(block.permutation.withState("r:stages", 1));
            player.dimension.runCommand(`playsound dig.grass @a ${block.x} ${block.y} ${block.z} 10 0.8`)
            if (selectedItem.amount > 1) {
                if (player.getGameMode() !== "creative"){
                        selectedItem.amount -= 1;
                }
                equipment.setEquipment('Mainhand', selectedItem);
            } else if (selectedItem.amount === 1 && player.getGameMode() !== "creative") {
                equipment.setEquipment('Mainhand', undefined);
            }
        })
    }
    else if(selectedItem && selectedItem.typeId == 'minecraft:bone_meal' && hasCrop != 'none' && !block.hasTag("MaxStage")){
        const currentState = block.permutation.getState("r:stages");
        system.run( () => {
            block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.center());
            block.dimension.playSound("item.bone_meal.use", block.center());
            if (selectedItem.amount > 1) {
                if (player.getGameMode() !== "creative"){
                        selectedItem.amount -= 1;
                }
                equipment.setEquipment('Mainhand', selectedItem);
            } else if (selectedItem.amount === 1 && player.getGameMode() !== "creative") {
                equipment.setEquipment('Mainhand', undefined);
            }

            if (block.hasTag("preMaxStage") && block.above().hasTag("WoodenStake")){
                const aboveState = block.above().permutation.getState("r:stages");
                const cropState = block.permutation.getState("r:crop");
                
                if ( (cropState == 'tomato' && aboveState == 0 && (block.below().hasTag("fertile_soil") || block.below().below().hasTag("fertile_soil") || block.below().typeId == "minecraft:farmland" || block.below().below().typeId == "minecraft:farmland")) || (cropState == 'chili' && aboveState == 0 && (block.below().hasTag("fertile_soil") || block.below().typeId == "minecraft:farmland"))){
                    block.above().setPermutation(block.above().permutation.withState("r:stages", 1));
                    block.above().setPermutation(block.above().permutation.withState("r:crop", cropState));
                }
            }

            block.setPermutation(block.permutation.withState("r:stages", currentState+1));
            
        })
    }


});



world.beforeEvents.playerInteractWithBlock.subscribe(eventData => {
    const player = eventData.player;
    const block = eventData.block;
    const item = eventData.itemStack;

    if (!block.hasTag("WoodenStake"))return;

    if (item != undefined) return;

    if (!player.isSneaking)return;

    const isLeashed = block.permutation.getState("r:leash");
    
    if(!isLeashed)return;

    eventData.cancel = true

    system.run( () => {
        if(block.north().hasTag("leashed")){
            block.north().setPermutation(block.north().permutation.withState("r:south", false));
            block.setPermutation(block.permutation.withState("r:north", false));
        }
        if(block.south().hasTag("leashed")){
            block.south().setPermutation(block.south().permutation.withState("r:north", false));
            block.setPermutation(block.permutation.withState("r:south", false));
        }
        if(block.east().hasTag("leashed")){
            block.east().setPermutation(block.east().permutation.withState("r:west", false));
            block.setPermutation(block.permutation.withState("r:east", false));
        }
        if(block.west().hasTag("leashed")){
            block.west().setPermutation(block.west().permutation.withState("r:east", false));
            block.setPermutation(block.permutation.withState("r:west", false));
        }
        block.setPermutation(block.permutation.withState("r:leash", false));
        player.getComponent('inventory').container.addItem(new ItemStack("rustic:rope", 1));
        player.dimension.runCommand(`playsound leashknot.break @a ${block.x} ${block.y} ${block.z}`)
    })
});

world.beforeEvents.playerBreakBlock.subscribe(eventData => {
    const block = eventData.block;

    if (!block.hasTag("WoodenStake"))return;

    const isLeashed = block.permutation.getState("r:leash");
    
    if(!isLeashed)return;

    const rope = new ItemStack("rustic:rope", 1)
    system.run( () => {
        eventData.dimension.spawnItem(rope,block.center())
    })
})