import { world, BlockPermutation, ItemStack, Direction } 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 getPreciseRotation(playerYRotation) {
    if (playerYRotation < 0)
        playerYRotation += 360;
    const rotation = Math.round(playerYRotation / 45);
    return rotation !== 8 ? rotation : 0;
}

function directionToVector3(direction) {
    switch (direction) {
        case Direction.Down:
            return { x: 0, y: -1, z: 0 };
        case Direction.Up:
            return { x: 0, y: 1, z: 0 };
        case Direction.North:
            return { x: 0, y: 0, z: -1 };
        case Direction.South:
            return { x: 0, y: 0, z: 1 };
        case Direction.West:
            return { x: -1, y: 0, z: 0 };
        case Direction.East:
            return { x: 1, y: 0, z: 0 };
    }
}

function getOppositeDirection(direction) {
    switch (direction) {
        case Direction.Up:
            return Direction.Down;
        case Direction.Down:
            return Direction.Up;
        case Direction.North:
            return Direction.South;
        case Direction.East:
            return Direction.West;
        case Direction.South:
            return Direction.North;
        case Direction.West:
            return Direction.East;
        default:
            break;
    }
}

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

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


const tortoise_egg = {
    onPlayerDestroy(event) {
        const { block, destroyedBlockPermutation } = event;
        const location = block.location;
        world.playSound('block.turtle_egg.break', location, { pitch: 0.9, volume: 0.85, } );
        const eggCount = destroyedBlockPermutation.getState('ph_wild:egg_count');
        if (eggCount > 1) {
            block.setPermutation(BlockPermutation.resolve(destroyedBlockPermutation.type.id, {
                ...destroyedBlockPermutation.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) {
            world.playSound('block.turtle_egg.break', location, { pitch: 0.9, volume: 0.85, } );

            if (eggCount == 1) world.getDimension("overworld").runCommand(`setblock ${location.x} ${location.y} ${location.z} air destroy`);
            if (eggCount > 1) world.getDimension("overworld").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) world.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) {
            world.getDimension("overworld").runCommand(`setblock ${location.x} ${location.y} ${location.z} air destroy`);
            world.playSound('mob.turtle_baby.born', location, { pitch: 1.0, volume: 1.0, } );
            if (eggCount >= 1) world.getDimension("overworld").spawnEntity('ph_wild:tortoise<entity_born>', location);
            if (eggCount >= 2) world.getDimension("overworld").spawnEntity('ph_wild:tortoise<entity_born>', location);
            if (eggCount >= 3) world.getDimension("overworld").spawnEntity('ph_wild:tortoise<entity_born>', location);
            if (eggCount >= 4) world.getDimension("overworld").spawnEntity('ph_wild:tortoise<entity_born>', location);
        }
    },
    onPlayerInteract(event) {
        const { block, player, face } = 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;
        world.getDimension("overworld").runCommand(`setblock ${location.x} ${location.y} ${location.z} ph_wild:tortoise_egg ["ph_wild:cracked_state"=0,"ph_wild:egg_count"=${eggCount}]`);
        world.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);
            world.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);
            world.playSound('fire.ignite', block.location, { pitch: 1.0, volume: 1.0, } );
        }
    }
};

world.beforeEvents.worldInitialize.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((brokenBlock) => {
    const player = brokenBlock.player;
    const block = brokenBlock.block;
    const permutation = brokenBlock.brokenBlockPermutation;
    const location = block.location;

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

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

    if (loot && Math.random() < loot_chance && !player.matches({ gameMode: 'creative' })) {
        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) } );
