import {ActionFormData} from "@minecraft/server-ui";
import {ItemStack, system, world} from "@minecraft/server";
import {saveInventory} from "inventory";

export function getScore(entity, scoreboard) {
    try {
        const score = world.scoreboard.getObjective(scoreboard).getScore(entity)
        if (score === undefined) {
            return 0;
        } else {
            return score;
        }
    } catch {
    }
    // console.warn(`scoreboard ${scoreboard} not found on ${entity.nameTag}`);
    return 0;
}

export function getClosestEntity(sourceEntity, identifier) {
    return sourceEntity.dimension.getEntities({
        type: identifier,
        closest: 1,
        location: sourceEntity.location,
        maxDistance: 10
    })[0];
}

let abilities_dict = {
    'winged_raptor': ['bite', 'fly', 'tracker', 'dismount'],
    'prehistoric_goat': ['headbutt', 'jump', 'activate_resistance', 'stun', 'dismount'],
    'predator_rex': ['bite', 'poison_bite', 'stun', 'tracker', 'add_hp', 'dismount'],
    'ankylosaurus': ['radius_knockback', 'standard_attack', 'activate_resistance', 'dismount'],
    'spineback_rex': ['poison_bite', 'speed_boost', 'dismount'],
    'mini_rex': ['bite', 'speed_boost', 'tracker', 'dismount'],
    'dodo': ['headbutt', 'speed_boost', 'tracker', 'jump', 'dismount'],
    'deinosuchus': ['poison_bite', 'add_hp', 'activate_resistance', 'dismount'],
    'triceratops': ['headbutt', 'stun', 'add_hp', 'activate_resistance', 'dismount'],
    'spiked_stalker': ['poison_bite', 'tracker', 'add_hp', 'dismount'],
    'infernosaur': ['fire_breath', 'activate_resistance', 'add_hp', 'dismount'],
    'lava_pup': ['fire_breath', 'speed_boost', 'dismount'],
    'infernal_raptor': ['bite', 'fire_breath', 'add_hp', 'tracker', 'dismount'],
    'infernal_rex': ['bite', 'fire_breath', 'tracker', 'stun', 'add_hp', 'dismount']
}

function startRiding(dino_entity) {
    let player = getClosestEntity(dino_entity, "minecraft:player");
    dino_entity.runCommand("scriptevent cubed:delay 1 \"/ride @p[tag=!is_riding, r=10] start_riding @s teleport_rider if_group_fits");

    saveInventory(player);
    setItems(player, dino_entity);
}

function setItems(player, dino_entity) {
    let zoneKey = dino_entity.typeId.replace("cubed:tame_", "");
    let items = abilities_dict[zoneKey];

    const playerInventory = player.getComponent('inventory').container;
    for (let i = 0; i < items.length; i++) {
        const itemStack = new ItemStack(`cubed:${items[i]}`);
        itemStack.lockMode = "slot";
        playerInventory.setItem(i, itemStack);
    }
}

export function open_menu(player) {
    const form = new ActionFormData();
    player.runCommand("tag @e remove selected_dino");
    player.runCommand("tag @e[family=tame, c=1, r=15] add selected_dino");

    const dino_entities = player.dimension.getEntities({
        tags: ["selected_dino"]
    });
    const dino_entity = dino_entities[0];
    const rawtext = {
        rawtext: [
            {
                translate: `entity.${dino_entity.typeId}.name`.replace('tame_', '')
            },
            {text: " Menu"},
        ],
    };
    form.title(rawtext)

    const menu_items = [
        {
            "name": "Stay in place",
            "component_name": "stay_in_place",
            "onClick": () => {
            },
            "icon": "barrier"
        },
        {
            "name": "Follow",
            "component_name": "follow",
            "onClick": () => {
            },
            "icon": "lead"
        },
        {
            "name": "Patrol",
            "component_name": "attack_enemies",
            "onClick": () => {
            },
            "icon": "iron_sword"
        },
        {
            "name": "Control dino",
            "component_name": "control_dino",
            "onClick": (lastActivity) => {
                dino_entity.runCommand(`scoreboard players set @s last_activity ${lastActivity}`)
                startRiding(dino_entity);
            },
            "icon": "saddle"
        },
        {
            "name": "Enable Armor",
            "component_name": "enable_armor",
            "onClick": () => {
            },
            "icon": "dino_armor"
        }
    ]

    let no_armors = [
        'dodo',
        'ankylosaurus',
        'predator_rex',
        'deinosuchus',
        'infernal_rex',
    ]

    for (const menu_data of menu_items) {
        let menu_text = menu_data["name"];
        let icon = menu_data["icon"];
        let component_name = menu_data["component_name"];

        if (component_name === "enable_armor") {

            if (!dino_entity.hasTag("has_armor")) {
                continue;
            }

            // Some dinos cant have armor.
            if (no_armors.some(substring => dino_entity.typeId.includes(substring))) {
                continue
            }

            if (dino_entity.getProperty("cubed:has_armor")) {
                menu_text = "Armor §2§lEnabled"
            } else {
                menu_text = "Armor §c§lDisabled"
            }
        }

        if ((component_name === "attack_enemies" || component_name === "follow") && dino_entity.typeId.includes("winged_raptor")) {
            continue;
        } else {
            form.button(menu_text, `textures/items/${icon}`);
        }
    }

    form.show(player).then((response) => {
        if (response.canceled) {
            return;
        }
        let responseIndex = response.selection;

        if (responseIndex >= 1 && dino_entity.typeId.includes("winged_raptor")) {
            responseIndex += 2;
        }

        let menu_item = menu_items[responseIndex];

        if (menu_item["component_name"] === "enable_armor") {
            let armorEnabled = dino_entity.getProperty("cubed:has_armor");
            dino_entity.setProperty("cubed:has_armor", !armorEnabled);

            if (armorEnabled) {
                player.sendMessage("Armor §c§lDisabled");
                dino_entity.triggerEvent("cubed:normal_health");
            } else {
                player.sendMessage("Armor §2§lEnabled");
                dino_entity.triggerEvent("cubed:armor_health");
            }
        } else {
            let lastActivity = getScore(dino_entity, "activity");
            dino_entity.runCommand(`event entity @s cubed:${menu_item["component_name"]}`)
            dino_entity.runCommand(`scoreboard players set @s activity ${responseIndex}`)
            menu_item["onClick"](lastActivity);
        }
    });
}



