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

export const block_list = {
    "minecraft:jungle_leaves": {
        loot: "ph_wild:banana",
        loot_chance: 0.1,
        loot_min_amount: 1,
        loot_max_amount: 3,
    },
};

function decrementStack(player) {
    if (player.getGameMode() === 'Creative') return;

    let inventory = player.getComponent('inventory').container;
    let item = inventory.getItem(player.selectedSlotIndex);
    if (item.amount == 1)
        inventory.setItem(player.selectedSlotIndex, undefined);
    else
        inventory.setItem(player.selectedSlotIndex, new ItemStack(item.typeId, item.amount - 1));
}


const tortoise_egg = {
    onPlayerBreak(event) {
        const { block, brokenBlockPermutation } = event;
        const location = block.location;
        block.dimension.playSound('block.turtle_egg.break', location, { pitch: 0.9, volume: 0.85, } );
        const eggCount = brokenBlockPermutation.getState('ph_wild:egg_count');
        if (eggCount > 1) {
            block.setPermutation(BlockPermutation.resolve(brokenBlockPermutation.type.id, {
                ...brokenBlockPermutation.getAllStates(),
                ['ph_wild:egg_count']: eggCount - 1
            }));
        }
    },
    onEntityFallOn(event) {
        const { block, fallDistance } = event;
        const location = block.location;
        const cardinalDirection = block.permutation.getState('minecraft:cardinal_direction');
        const crackedState = block.permutation.getState('ph_wild:cracked_state');
        const eggCount = block.permutation.getState('ph_wild:egg_count');
        if (fallDistance > 0.5 && Math.random()<=0.33) {
            block.dimension.playSound('block.turtle_egg.break', location, { pitch: 0.9, volume: 0.85, } );

            if (eggCount == 1) block.dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} air destroy`);
            if (eggCount > 1) block.dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} ph_wild:tortoise_egg ["minecraft:cardinal_direction"="${cardinalDirection}","ph_wild:cracked_state"=${crackedState},"ph_wild:egg_count"=${eggCount-1}] destroy`);
        }
    },
    onTick(event) {
        const { block } = event;
        const location = block.location;
        const crackedState = block.permutation.getState('ph_wild:cracked_state');
        const eggCount = block.permutation.getState('ph_wild:egg_count');

        if (crackedState == 4 || crackedState == 7) block.dimension.playSound('block.turtle_egg.crack', location, { pitch: 1.0, volume: 1.0, } );

        if (crackedState < 10) block.setPermutation(block.permutation.withState('ph_wild:cracked_state', crackedState + 1));

        if (crackedState == 10) {
            block.dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} air destroy`);
            block.dimension.playSound('mob.turtle_baby.born', location, { pitch: 1.0, volume: 1.0, } );
            if (eggCount >= 1) block.dimension.spawnEntity('ph_wild:tortoise', location, { spawnEvent: 'entity_born' });
            if (eggCount >= 2) block.dimension.spawnEntity('ph_wild:tortoise', location, { spawnEvent: 'entity_born' });
            if (eggCount >= 3) block.dimension.spawnEntity('ph_wild:tortoise', location, { spawnEvent: 'entity_born' });
            if (eggCount >= 4) block.dimension.spawnEntity('ph_wild:tortoise', location, { spawnEvent: 'entity_born' });
        }
    },
    onPlayerInteract(event) {
        const { block, player } = event;
        const mainhand = player.getComponent('equippable').getEquipment('Mainhand');

        if (mainhand === undefined) return;

        if (mainhand.typeId != 'ph_wild:tortoise_egg') return;

        const eggCount = block.permutation.getState('ph_wild:egg_count');
        if (eggCount < 4) {
            block.setPermutation(block.permutation.withState('ph_wild:egg_count', eggCount + 1));
            block.dimension.playSound("use.stone", block.location, { pitch: 0.8, volume: 1.0 });
            decrementStack(player);
        }
    }
};
const tortoise_egg_lay = {
    onPlace(event) {
        const { block } = event;
        const location = block.location;
        const eggCount = Math.floor(Math.random() * (4 - 1 + 1)) + 1;
        block.dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} ph_wild:tortoise_egg ["ph_wild:cracked_state"=0,"ph_wild:egg_count"=${eggCount}]`);
        block.dimension.playSound('block.turtle_egg.drop', location, { pitch: 0.9, volume: 0.3, } );
    },
};

const animal_fat_torch = {
    onPlayerInteract(event) {
        const { block } = event;
        const activeState = block.permutation.getState('ph_wild:ative');
        if (activeState) {
            let newPermutation = BlockPermutation.resolve(block.typeId, {
                ...block.permutation.getAllStates(),
                'ph_wild:ative': false
            });
            block.setPermutation(newPermutation);
            block.dimension.playSound('random.fizz', block.location, { pitch: 1.0, volume: 1.0, } );
        }
        if (!activeState) {
            let newPermutation = BlockPermutation.resolve(block.typeId, {
                ...block.permutation.getAllStates(),
                'ph_wild:ative': true
            });
            block.setPermutation(newPermutation);
            block.dimension.playSound('fire.ignite', block.location, { pitch: 1.0, volume: 1.0, } );
        }
    }
};

system.beforeEvents.startup.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent("ph_wild:tortoise_egg", tortoise_egg);
    blockComponentRegistry.registerCustomComponent("ph_wild:tortoise_egg.lay", tortoise_egg_lay);
    //blockComponentRegistry.registerCustomComponent("ph_wild:animal_fat_torch", animal_fat_torch);
});

world.afterEvents.playerBreakBlock.subscribe(({ player, block, brokenBlockPermutation }) => {
    if (player.getGameMode() !== 'Survival' && player.getGameMode() !== 'Adventure') return;

    const location = block.location;

    const blockData = block_list[brokenBlockPermutation?.type.id];

    const { loot, loot_chance, loot_min_amount, loot_max_amount } = blockData;

    const inventory = player.getComponent('inventory').container;
    const item = inventory.getItem(player.selectedSlotIndex);
    const enchantment = item?.getComponent('enchantable');

    if (item?.typeId === 'minecraft:shears' || enchantment?.hasEnchantment('silk_touch')) return;

    if (loot && Math.random() < loot_chance) {
        const amount = Math.floor(Math.random() * (loot_max_amount - loot_min_amount + 1)) + loot_min_amount;
        const centerLocation = {
            x: location.x + 0.5,
            y: location.y + 0.5,
            z: location.z + 0.5
        };
        const item = new ItemStack(loot, amount);
        block.dimension.spawnItem(item, centerLocation);
    }

}, { blockTypes: Object.keys(block_list) } );
