import { system, world, ItemStack } from "@minecraft/server";
import "petBeds.js";
import "./gui/index.js";
import {lootTable} from "lootingDB.js";

const lootingPets = new Set ([
    "md_bap:white_tiger",
    "md_bap:dingo",
    "md_bap:leopard",
    "md_bap:lion",
    "md_bap:tiger",
    "md_bap:black_bear",
    "md_bap:polar_bear",
    "md_bap:bear",
    "md_bap:crocodile",
    "md_bap:hyena",
    "md_bap:jackal",
    "md_bap:wolf",
    "md_bap:maned_wolf"
]);

system.afterEvents.scriptEventReceive.subscribe(event => {
    const mob = event.sourceEntity;
    if (event.id.startsWith("md_bap:effect")) {
        const data = event.id.split(".");
            const type = data[1];
            const lvl = data[2] *1;
            const dura = (data[3] * 20)+200; //value of the duration in ticks plus 10 seconds extra
            const targetPlayers = mob.dimension.getEntities({location: mob.location, maxDistance: 50 }).filter(e => e.typeId === "minecraft:player" || (e.typeId.includes("md_bap:") && e.typeId !== "md_bap:seat"));
            //Applies to pets and players
            if (!targetPlayers || targetPlayers.length === 0) {
                return;
            }
            targetPlayers.forEach(e => {
                try {
                    e.addEffect(type,dura,{amplifier:lvl,showParticles:true})
                } catch (e) {
                };            
            });
    } else if (event.id === "md_bap:remove_bed") {
        const bedEntity = mob.dimension.getEntities({location: mob.location, maxDistance: 1 }).filter(e => e.typeId === "md_bap:seat")[0];
        if (!bedEntity) return;
        bedEntity.triggerEvent("despawn");
    } else if (event.id === "md_bap:leash") {
        mob.addTag("on_lead")
    } else if (event.id === "md_bap:unleash") {
        mob.removeTag("on_lead")
    } else if (event.id === "md_bap:tag_owner") {
        const owner = mob.dimension.getEntities({location: mob.location, maxDistance: 7 }).filter(e => e.typeId === "minecraft:player")[0];
        mob.addTag(owner.id)
    }
  });

  world.afterEvents.entityDie.subscribe((e) => {
    const {damageSource, deadEntity: entity} = e;
    if (!damageSource.damagingEntity) return; //Check that its another entity that caused damage
    if (!lootingPets.has(damageSource.damagingEntity.typeId)) return; //Check if the entity damaging is in the set
    
    const loot = lootTable[entity.typeId];
    if (!loot || loot.length === 0) return; // No loot table or items defined for this mob
    const dimension = entity.dimension;
    
    loot.forEach(drop => {
        if (Math.random() <= drop.chance) {
            const qty = Math.floor(Math.random() * (drop.max_qty - drop.min_qty + 1)) + drop.min_qty;
            const itemStack = new ItemStack(drop.item, qty);
            dimension.spawnItem(itemStack, entity.location);
        }
    });
});