import { world, system, Vector, EquipmentSlot, BlockPermutation } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";
import { setTimeout } from "./timers.js";
import { portal } from "./portal/portal.js";
import { slimeSkin } from "./slimeSkin.js";
import { obeliskSpawnPoint } from "./obelisk.js"
import { chests } from "./chests.js"

system.beforeEvents.watchdogTerminate.subscribe(data => {
    data.cancel = true;
});

obeliskSpawnPoint();

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const { x, y, z } = player.location;
        const biomeBlocks = [
            {
                block: 'end_moss',
                tag: 'foggy_mushroomland',
                fog: 'betterend:foggy',
                sound: 'foggy_mushroomland',
                music: 'betterend.calm.music',
            },
            {
                block: 'amber_moss',
                tag: 'amberland',
                fog: 'betterend:amberland',
                sound: 'amber_land',
                music: 'betterend.calm.music',
            },
            {
                block: 'pink_moss',
                tag: 'blossoming_spire',
                fog: 'betterend:blossoming',
                sound: 'blossoming_spires',
                music: 'betterend.calm.music',
            },
            {
                block: 'crystal_moss',
                tag: 'crystal_moutains',
                fog: 'betterend:crystal',
                sound: 'foggy_mushroomland',
                music: 'betterend.caves.music',
            },
            {
                block: 'chorus_nylium',
                tag: 'chorus_forest',
                fog: 'betterend:chorus_forest',
                sound: 'chorus_forest',
                music: 'betterend.forest.music',
            },
            {
                block: 'endstone_dust',
                tag: 'dust_wasteland',
                fog: 'betterend:dust',
                sound: 'dust_wastelands',
                music: 'betterend.dark.music',
            },
            {
                block: 'end_moss_neon_oasis',
                tag: 'neon_oasis',
                fog: 'betterend:dust',
                sound: 'dust_wastelands',
                music: 'betterend.dark.music',
            },
            {
                block: 'end_moss_lakes',
                tag: 'megalakes',
                fog: 'betterend:megalakes',
                sound: 'megalake',
                music: 'betterend.calm.music',
            },
            {
                block: 'shadow_grass',
                tag: 'shadow_forest',
                fog: 'betterend:shadow',
                sound: 'chorus_forest',
                music: 'betterend.dark.music',
            },
            {
                block: 'sulphur_springs',
                tag: 'sulphur_springs',
                fog: 'betterend:sulphur',
                sound: 'sulphur_springs',
                music: 'none',
            },
            {
                block: 'jungle_moss',
                tag: 'umbrella_jungle',
                fog: 'betterend:umbrella',
                sound: 'umbrella_jungle',
                music: 'betterend.calm.music',
            },
            {
                block: 'end_moss_glow',
                tag: 'glowing_grasslands',
                fog: 'betterend:glowing_grasslands',
                sound: 'glowing_grasslands',
                music: 'betterend.calm.music',
            },
            {
                block: 'sangnum',
                tag: 'dragon_graveyards',
                fog: 'betterend:dragon_graveyards',
                sound: 'amber_land',
                music: 'betterend.calm.music',
            },
            {
                block: 'rutiscus',
                tag: 'dry_shrubland',
                fog: 'betterend:dry',
                sound: 'chorus_forest',
                music: 'betterend.forest.music',
            }
        ];
        const caveBiomesBlocks = [
            {
                block: 'cave_moss',
                tag: 'lush_cave',
                fog: 'betterend:lush_cave',
                sound: 'caves',
                music: 'betterend.caves.music',
            },
            {
                block: 'jadestone',
                tag: 'jadestone',
                fog: 'betterend:jadestone',
                sound: 'caves',
                music: 'betterend.caves.music',
            },
            {
                block: 'cave_moss_smaragdant',
                tag: 'smaragdant',
                fog: 'betterend:smaragdant',
                sound: 'caves',
                music: 'betterend.caves.music',
            }
        ]
        if (player.dimension.id == 'minecraft:overworld' && player.hasTag('the_end')) {
            player.removeTag('the_end');
            player.addTag('endStoneFog');
            player.removeTag('in_biome');
            player.runCommandAsync('fog @s remove end_fog');
            for (const biomeBlock of biomeBlocks) {
                player.removeTag(biomeBlock.tag);
            }
        }
        if (player.dimension.id == 'minecraft:the_end') {
            player.addTag('the_end');
            for (let i = 55; i <= 64; i++) { // Ajusta el rango de alturas aquí
                const blockGround = player.dimension.getBlock(new Vector(x, i, z)).typeId;
                const blockTag = player.dimension.getBlock(new Vector(x, i, z)).getTags();
                if (y > 55) {
                    for (const biomeBlock of biomeBlocks) {
                        if (blockGround == `betterend:${biomeBlock.block}` && !player.hasTag('endStoneFog')) {
                            player.addTag(`${biomeBlock.tag}`);
                            fogSoundsMusic(player, biomeBlock.fog, biomeBlock.sound, biomeBlock.music, 1000);
                        }
                        else if (!player.hasTag('endStoneFog') && blockTag.includes('sulphur_springs')) {
                            player.addTag(`sulphur_springs`);
                            fogSoundsMusic(player, 'betterend:sulphur', 'sulphur_springs', 'none', 1000);
                        }
                    }
                }
            }
            for (let i = 45; i >= 10; i--) { // Ajusta el rango de alturas aquí
                const blockGround = player.dimension.getBlock(new Vector(x, i, z)).typeId;
                const blockTag = player.dimension.getBlock(new Vector(x, i, z)).getTags();
                if (y < 45) {
                    for (const biomeBlock of caveBiomesBlocks) {
                        if (blockGround == `betterend:${biomeBlock.block}` && !player.hasTag('endStoneFog')) {
                            player.addTag(`${biomeBlock.tag}`);
                            fogSoundsMusic(player, biomeBlock.fog, biomeBlock.sound, biomeBlock.music, 1000);
                        }
                        else if (!player.hasTag('endStoneFog') && blockTag.includes('jadestone')) {
                            player.addTag(`jadestone`);
                            fogSoundsMusic(player, 'betterend:jadestone', 'caves', 'betterend.caves.music', 1000);
                        }
                    }
                }
            }

            const normalBlock = player.dimension.getBlock(new Vector(x, y - 1, z)).typeId;
            const blockTag = player.dimension.getBlock(new Vector(x, y - 1, z)).getTags();
            if (normalBlock == 'minecraft:end_stone') {
                player.addTag('endStoneFog');
                player.removeTag('in_biome');
                player.runCommandAsync('fog @s remove end_fog');
                for (const biomeBlock of biomeBlocks) {
                    player.removeTag(biomeBlock.tag);
                }
            }
            else {
                player.removeTag('endStoneFog');
            }
        }

        function fogSoundsMusic(player, fog, sound, music, time) {
            if (!player.hasTag('in_biome')) {
                player.addTag('in_biome');
                player.runCommandAsync(`stopsound @s`);
                player.runCommandAsync(`fog @s remove end_fog`);
                player.runCommandAsync(`fog @s push ${fog} end_fog`);
                setTimeout(() => {
                    player.playSound(sound, { location: player.location });
                    player.playSound(music, { location: player.location, volume: 0.3 });
                }, time);
            }
        }

        const allBiomeTags = [...biomeBlocks, ...caveBiomesBlocks].map(biomeBlock => biomeBlock.tag);
        const matchingTags = allBiomeTags.filter(tag => player.hasTag(tag));

        if (matchingTags.length >= 2) {
            player.removeTag('in_biome');
            for (const biomeBlock of allBiomeTags) {
                player.removeTag(biomeBlock);
            }
        }

    }
}, 20);

system.runInterval(async () => {
    for (const player of world.getPlayers()) {
        const equipment = player.getComponent("minecraft:equippable");
        const helmet = equipment?.getEquipment(EquipmentSlot.Head);
        const chestplate = equipment?.getEquipment(EquipmentSlot.Chest);
        const feet = equipment?.getEquipment(EquipmentSlot.Feet);
        const legs = equipment?.getEquipment(EquipmentSlot.Legs);
        if (helmet) {
            if (helmet.typeId == 'betterend:crystalite_helmet') {
                if (!player.getEffect('regeneration')) {
                    player.addEffect('regeneration', 100, { showParticles: false });
                }
            }
        }
        if (chestplate) {
            if (chestplate.typeId == 'betterend:crystalite_chestplate') {
                player.addEffect('haste', 100, { showParticles: false });
            }
        }
        if (feet) {
            if (feet.typeId == 'betterend:crystalite_boots') {
                player.addEffect('speed', 100, { showParticles: false });
            }
        }
        if (legs) {
            if (legs.typeId == 'betterend:crystalite_leggings') {
                player.addEffect('health_boost', 100, { showParticles: false });
            }
        }
    }
});

system.runInterval(async () => {

    for (const entities of world.getDimension('overworld').getEntities()) {
        //chests
        chests(entities, Vector, BlockPermutation);
        //slimesSkin
        slimeSkin(entities, Vector);

        //portal crystals
        if (entities.typeId == 'betterend:check_portal') {
            const { successCount: crystals } = await entities.runCommandAsync(`testfor @e[type=betterend:eternal_crystal_entity,r=7,c=6]`);
            if (crystals == 6) {
                entities.runCommandAsync(`tag @p[r=2,tag=!teleport_to_overworld] add teleport_to_overworld`);
                if (!entities.hasTag('portal_put')) {
                    entities.addTag('portal_put');
                    await entities.runCommandAsync(`structure load open_portal ~ ~ ~-2`);
                }
            }
            else if (crystals < 6 && entities.hasTag('portal_put')) {
                entities.removeTag('portal_put');
                await entities.runCommandAsync(`structure load close_portal ~ ~ ~-2`);
            }
        }
        if (entities.typeId == 'betterend:check_portal_overworld') {
            entities.runCommandAsync(`tag @p[r=2,tag=!teleport_to_end] add teleport_to_end`);
        }
    }
    for (const player of world.getPlayers()) {

        //obelisk

        if (player.hasTag('waiting_obelisk')) {
            player.removeTag('waiting_obelisk');
            const playerSpawns = player.getTags();
            const endSpawnTag = playerSpawns.find(tag => tag.includes("endspawn"));
            const coords = endSpawnTag.split(':')[2].split(' ');
            setTimeout(() => {
                player.teleport(new Vector(parseInt(coords[0]), parseInt(coords[1]), parseInt(coords[2])), { dimension: world.getDimension("the end") });
                player.removeTag(endSpawnTag);
            }, 5000);
        }

        //portal

        portal();

        //equipment
    }
});

world.beforeEvents.itemUseOn.subscribe(async evd => {
    const { source: player, itemStack: item, block } = evd;

    if (item.typeId == 'betterend:eternal_crystal' && block.typeId == 'betterend:eternal_pedestal_off' && !player.isSneaking) {
        try {
            system.run(async () => {
                await player.runCommandAsync(`clear @s betterend:eternal_crystal 0 1`);
                await player.playSound('beacon.power', { location: player.location, volume: 1 })
            });
        } catch (e) { console.warn(e) }
    }
});

world.beforeEvents.itemUseOn.subscribe(async evd => {
    const { source: player, block, itemStack: item } = evd;

    system.run(() => {
        if (item.typeId == 'minecraft:stick' && !player.isSneaking) {
            try {
                const indexTag = player.getTags().find(tag => tag.includes('index:'));
                const color = block.permutation.withState('betterend:color', parseInt(indexTag.split(':')[1]));
                block.setPermutation(color);
            } catch {
                player.removeTag('inCooldown');
            }
        }
        if (!player.hasTag('inCooldown') && item.typeId == 'minecraft:stick' && player.isSneaking) {
            player.addTag('inCooldown');
            player.addTag('indexform');
        }
    });
});


system.runInterval(() => {
    for (const player of world.getPlayers()) {
        if (player.hasTag('indexform')) {
            player.removeTag('indexform');
            let index = new ModalFormData()
                .slider('Index', 0, 7, 1, 0)
                .show(player)
                .then(scb => {
                    const rs = scb.formValues[0];
                    const indexTag = player.getTags().find(tag => tag.includes('index:'));
                    player.removeTag(indexTag);
                    player.addTag(`index:${rs}`);
                    player.removeTag('inCooldown');
                })
                .catch(() => {
                    player.removeTag('inCooldown');
                })
                .finally(() => {
                    player.removeTag('inCooldown');
                });
        }
    }
});





world.afterEvents.playerPlaceBlock.subscribe(evd => {
    const { block, player } = evd;
    const { x, y, z } = block.location;
    const chestsID = ["umbrella_tree_chest", "tenanea_chest", "pythadendron_chest", "lucernia_chest", "lacugrove_chest", "jellyshroom_chest", "helix_tree_chest", "end_lotus_chest", "dragon_tree_chest"];
    for (const chest of chestsID) {
        if (block.typeId.includes(chest)) {
            const chest = player.dimension.spawnEntity('betterend:chest_test', new Vector(x, y, z));
            setTimeout(() => {
                chest.teleport(new Vector(x + 0.5, y, z + 0.5));
            }, 1000);
        }
    }
});