import { GameMode, ItemStack, system, world } from "@minecraft/server";
import Random from "./_Utilities/Random";
import Vector from "./_Utilities/Vector";
import Buffer from "./_Utilities/Buffer";
import { MinecraftItemTypes } from "./_Utilities/vanilla-data/mojang-item";
import { MinecraftEntityTypes } from "./_Utilities/vanilla-data/mojang-entity";
import Progression_Manager from "./Progression/Progression_Manager";
import Block_Manager from "./Block/Block_Manager";
import Command_Manager from "./Command/Command_Manager";
import Biome_Manager from "./Biome/Biome_Manager";
import Actor_Persistent_Manager from "./Actor/Managers/Actor_Persistent_Manager";
import Quest_Manager from "./Quest/Quest_Manager";
import Entity_Inventory_Manager from "./Entity/Managers/Entity_Inventory_Manager";
import Dialog_Form from "./Form/Data/Custom Forms/Dialog_Form";
import Film_Manager from "./Film/Film_Manager";
system.runInterval(() => {
    const players = world.getAllPlayers();
    for (let i = 0; i < players.length; i++) {
        const shard_Desert = Entity_Inventory_Manager.count_Item(players[i], "bgs:shard_desert");
        const shard_Forest = Entity_Inventory_Manager.count_Item(players[i], "bgs:shard_forest");
        const shard_Mesa = Entity_Inventory_Manager.count_Item(players[i], "bgs:shard_mesa");
        const shard_Mountain = Entity_Inventory_Manager.count_Item(players[i], "bgs:shard_mountain");
        const shard_Ocean = Entity_Inventory_Manager.count_Item(players[i], "bgs:shard_ocean");
        const shown = Buffer.get_Data("4c6f4fa7-a189-4d61-8f05-48e4f69639de", players[i].id);
        if (shown == undefined) {
            if (shard_Desert >= 1 && shard_Forest >= 1 && shard_Mesa >= 1 && shard_Mountain >= 1 && shard_Ocean >= 1) {
                players[i].onScreenDisplay.setTitle("§cNether Island§f", {
                    subtitle: "Unlocked",
                    fadeInDuration: 20,
                    fadeOutDuration: 10,
                    stayDuration: 20,
                });
                Buffer.set_Data("4c6f4fa7-a189-4d61-8f05-48e4f69639de", players[i].id, true);
            }
        }
        else if (shown == true) {
            if (shard_Desert == 0 || shard_Forest == 0 || shard_Mesa == 0 || shard_Mountain == 0 || shard_Ocean == 0) {
                Buffer.set_Data("4c6f4fa7-a189-4d61-8f05-48e4f69639de", players[i].id, undefined);
            }
        }
        Actor_Persistent_Manager.runtime(players[i].dimension.id, players[i].location);
        Biome_Manager.runtime(players[i]);
        if (Biome_Manager.get_Area_ID(players[i].location) != "044fc572-27ae-4faf-8d16-2c31cb989122")
            continue;
        if (shard_Desert == 0 || shard_Forest == 0 || shard_Mesa == 0 || shard_Mountain == 0 || shard_Ocean == 0) {
            players[i].sendMessage("Area not unlocked yet");
            const center = { x: -22.5, y: players[i].location.y, z: 394.5 };
            const ab = Vector.subtract(players[i].location, center);
            players[i].applyKnockback(ab.x, ab.z, 2, 0.25);
        }
    }
}, 20);
world.afterEvents.worldInitialize.subscribe((event) => {
    Progression_Manager.initialize();
    Actor_Persistent_Manager.initialize();
    world.setDefaultSpawnLocation({ x: 100.5, y: 91, z: 103.5 });
    world.gameRules.doMobSpawning = false;
    world.gameRules.showCoordinates = true;
    const players = world.getAllPlayers();
    for (let i = 0; i < players.length; i++) {
        players[i].inputPermissions.cameraEnabled = true;
        players[i].inputPermissions.movementEnabled = true;
    }
});
world.afterEvents.playerSpawn.subscribe((event) => {
    const player = event.player;
    if (event.initialSpawn) {
        player.inputPermissions.cameraEnabled = true;
        player.inputPermissions.movementEnabled = true;
        player.setGameMode(GameMode.survival);
        spawn_UI(player);
    }
    else {
        player.inputPermissions.cameraEnabled = true;
        player.inputPermissions.movementEnabled = true;
        if (Entity_Inventory_Manager.count_Item(player, "bgs:book_guide") == 0) {
            Entity_Inventory_Manager.add_Item(player, {
                id: "bgs:book_guide",
                name_Tag: "Guide Book",
                lore: ["Interact with the Book to open the UI"],
            });
        }
    }
});
world.afterEvents.playerBreakBlock.subscribe((event) => {
    const player = event.player;
    const block = event.block;
    const permutation = event.brokenBlockPermutation;
    Block_Manager.break(player, block, permutation);
});
world.afterEvents.itemUse.subscribe((event) => {
    const player = event.source;
    const item = event.itemStack;
    if (item.typeId == "bgs:book_guide") {
        const books = player.dimension.getEntities({ type: "bgs:guide_book" });
        for (let i = 0; i < books.length; i++) {
            books[i].remove();
        }
        const roation = player.getRotation();
        const ray = player.getBlockFromViewDirection();
        player.playSound("item.book.page_turn");
        player.runCommand("summon bgs:guide_book ^ ^ ^2 facing @s");
    }
});
world.afterEvents.entityHitBlock.subscribe((event) => {
    const player = event.damagingEntity;
    const block = event.hitBlock;
    const permutation = event.hitBlockPermutation;
    Block_Manager.hit(player, block, permutation);
});
world.afterEvents.entityDie.subscribe((event) => {
    const entity = event.deadEntity;
    const attacker = event.damageSource.damagingEntity;
    if (entity.typeId != "minecraft:item") {
        if (entity.hasTag("raider")) {
            const amount = Random.integer(4, 32);
            const item = new ItemStack(MinecraftItemTypes.Emerald, amount);
            entity.dimension.spawnItem(item, entity.location);
        }
        if (attacker != undefined) {
            if (attacker.typeId == MinecraftEntityTypes.Player)
                Quest_Manager.defeated(entity);
        }
    }
});
world.afterEvents.entityHitEntity.subscribe((event) => {
    const attacked = event.hitEntity;
    if (attacked.typeId == "bgs:guide_book") {
        attacked.playAnimation("animation.guide_book.close2");
        system.runTimeout(() => {
            attacked.remove();
        }, 20);
    }
});
system.afterEvents.scriptEventReceive.subscribe((event) => {
    Command_Manager.run(event);
});
function spawn_UI(player) {
    const progression = Progression_Manager.get("dc572846-b8ec-4089-8038-b363975b9c7e");
    if (progression.shown_Cinematics.includes("9680306d-ca20-4ddd-b44a-fc5b2c70c0d1"))
        return;
    player.setSpawnPoint({ dimension: world.getDimension("overworld"), x: 100.5, y: 91, z: 103.5 });
    player.teleport({ x: 100.5, y: 91, z: 103.5 });
    system.runTimeout(async () => {
        const form = new Dialog_Form();
        form.title("Mellino");
        form.body("Hello {NAME}, I am Mellino.\nAre you ready to start your adventure?".replaceAll("{NAME}", player.name));
        form.button("Yes!");
        form.texture("textures/ui/dialog/quadruped_mellino");
        const result = await form.show(player);
        if (result?.selection == 0) {
            const film_ID = Biome_Manager.get("0a809bc5-5690-47d6-a96b-7e2360d26df4").film_ID;
            Film_Manager.play(player, film_ID, 0);
            const progression = Progression_Manager.get("dc572846-b8ec-4089-8038-b363975b9c7e");
            progression.shown_Cinematics.push("9680306d-ca20-4ddd-b44a-fc5b2c70c0d1");
            Progression_Manager.set(progression);
            return;
        }
        spawn_UI(player);
    }, 20);
}
