import { world,system,ItemStack } from "@minecraft/server";
import { findMarried } from "../items/artifacts/soulbound_ring.js";
import { deadlyRuby } from "../items/artifacts/artifacts.js";
import { SpearsNormalAttack } from "../items/spears.js";


function isFamily(family,entity) {
    return entity?.getComponent('minecraft:type_family')?.hasTypeFamily(family)
}






world.afterEvents.entityHitEntity.subscribe((evd) => {
    const hitEntity = evd.hitEntity
    const entity = evd.damagingEntity
    SpearsNormalAttack(hitEntity,entity)
    if(hitEntity.typeId == "edx:whomper" && hitEntity?.getProperty('edx:parry')==2)
    {
        const player = entity;
        const rocky = hitEntity;
        const power = Math.sqrt(rocky.getViewDirection().x ** 2 + rocky.getViewDirection().z ** 2 + rocky.getViewDirection().y ** 2)*7.5
        rocky.applyKnockback({x:rocky.getViewDirection().x*power, z:rocky.getViewDirection().z*power}, 0.4)
        rocky.triggerEvent('can_parry')
        player.applyDamage(15,{cause: "entityAttack",damagingEntity:victim})
    }
    if (entity.typeId == "edx:rocket_walker") {
        const player = hitEntity;
        const rocky = entity;
        const power = Math.sqrt(rocky.getViewDirection().x ** 2 + rocky.getViewDirection().z ** 2 + rocky.getViewDirection().y ** 2)*3.5
        player.applyKnockback({x:rocky.getViewDirection().x*power, z:rocky.getViewDirection().z*power}, 0.4)
    } 
    if (entity.typeId == "edx:behemoth") {
        hitEntity.applyKnockback({x:0, z:0}, 1.5)
    } 
    if ((evd.hitEntity.typeId === 'minecraft:skeleton' ) && (evd.damagingEntity.hasTag("tormented_soul"))) {
        evd.hitEntity.runCommand(`event entity @s soul_screamer_timer`);
        evd.damagingEntity.runCommand(`event entity @s despawn`); 
    }
    if ((evd.hitEntity.typeId === 'minecraft:skeleton' ) && (evd.damagingEntity.hasTag("crying_soul"))) {
        evd.hitEntity.runCommand(`event entity @s soul_necromancer_timer`);
        evd.damagingEntity.runCommand(`event entity @s despawn`); 
    }
    if ((evd.hitEntity.typeId === 'minecraft:skeleton' ) && (evd.damagingEntity.hasTag("enraged_soul"))) {
        evd.hitEntity.runCommand(`event entity @s angry_skeleton_timer`);
        evd.damagingEntity.runCommand(`event entity @s despawn`); 
    }
    if (evd.hitEntity.hasTag("sneak") ) {
        const equipment = evd.hitEntity.getComponent('equippable'); 
        const selectedItem =  equipment.getEquipment('Mainhand') ;
        const selectedItemOffhand = equipment.getEquipment('Offhand')
        if (selectedItem && selectedItem.typeId === 'minecraft:shield' && selectedItem.getComponent("cooldown").getCooldownTicksRemaining(evd.hitEntity) === 0 ) {
            selectedItem.getComponent("cooldown").startCooldown(evd.hitEntity)
        }
        if (selectedItemOffhand && selectedItemOffhand.typeId === 'minecraft:shield' && selectedItemOffhand.getComponent("cooldown").getCooldownTicksRemaining(evd.hitEntity) === 0 ) {
            selectedItemOffhand.getComponent("cooldown").startCooldown(evd.hitEntity)
        }
    }
    
    if(hitEntity.typeId == 'minecraft:player')
        deadlyRuby(hitEntity)
    if(entity.typeId === 'minecraft:player' && entity?.hasTag("soul_mirror") && !entity.hasTag("already_soul_mirror"))
    {
        
        const marriedentity = findMarried(entity)
        if(marriedentity != undefined )
        {
            if(!marriedentity.hasTag('already_soul_mirror'))
                {
                    const soul = entity.dimension.spawnEntity("edx:mirror_soul", entity.location);
                    soul.triggerEvent("married")
                    soul.getComponent("minecraft:tameable").tame(entity)
                    entity.addTag("already_soul_mirror")
                    entity.runCommand(`scoreboard players set @s Married_soul 120`)
                }
        }
        else
        {
            const soul = entity.dimension.spawnEntity("edx:mirror_soul", entity.location);
            soul.triggerEvent("non_married")
            soul.getComponent("minecraft:tameable").tame(entity)
            entity.addTag("already_soul_mirror")
            entity.runCommand(`scoreboard players set @s Married_soul 120`)
        }
        
    }
    if(hitEntity.typeId === 'minecraft:player' && hitEntity?.hasTag("corrupted_star"))
    {
        const scoreboard = world.scoreboard.getObjective("Wither_ribs");
        if(scoreboard.getScore(hitEntity)==0)
        {
            const ribs = hitEntity.dimension.spawnEntity("edx:wither_ribs", hitEntity.location);
            ribs.getComponent("minecraft:tameable").tame(hitEntity)
            scoreboard.setScore(hitEntity,140)
        }
    }
            
        
    if (entity.typeId === 'minecraft:player' && hitEntity.typeId === 'edx:volley_bomb') {
        const player = entity;
        const bomb = hitEntity;
        const power = Math.sqrt(player.getViewDirection().x ** 2 + player.getViewDirection().z ** 2)*4
        bomb.applyKnockback({x:player.getViewDirection().x*power, z:player.getViewDirection().z*power}, player.getViewDirection().y*1.3)
    }

    
    if ((isFamily('monster', hitEntity) === true || isFamily('mob', hitEntity) === true) && entity.typeId === 'edx:neoplasm_spider') {
        const mob = hitEntity;
        let health = mob.getComponent("health")
        if (health.currentValue === 0) {
            hitEntity.runCommand(`summon edx:small_neoplasm_spider`);
        }
    }

    if ((hitEntity.typeId === 'minecraft:creeper' || hitEntity.typeId === 'edx:big_creeper') && (entity.typeId === 'edx:neoplasm_spider' || entity.typeId === 'edx:small_neoplasm_spider')) {
        const mob = hitEntity;
        mob.remove()
    }

    if (entity.typeId === 'minecraft:player') {

        if ( entity?.getComponent("minecraft:inventory")?.container?.getItem(entity.selectedSlotIndex)?.typeId === 'edx:spider_mandibule' && (isFamily('monster', hitEntity) === true || isFamily('mob', hitEntity) === true)) {
            hitEntity.runCommand(`tag @s add bleeding`);
            hitEntity.runCommand(`tag @s remove bleeding4`);
            hitEntity.runCommand(`tag @s remove bleeding3`);
            hitEntity.runCommand(`tag @s remove bleeding2`);
            hitEntity.runCommand(`tag @s remove bleeding1`);
            
            }
        
    }

    if(hitEntity.typeId == "edx:wither" && hitEntity.getComponent(`health`).currentValue == 0)
    {
        const position =hitEntity.location
        const dimension = hitEntity.dimension
        const entityOptions = {
            location: position,
            families: [ "player" ],
            maxDistance: 50
        }
        const entities = dimension.getEntities(entityOptions);
        if(!hitEntity.hasTag("wither"))
            for (let i = 0; i < entities.length ; i++){
                entities[i].runCommand(`scoreboard players add @s[tag=!wither] max_health 4`)
                entities[i].runCommand(`tellraw @s[tag=!wither] { "rawtext": [ { "translate": "message.event.wither" } ] }`)
                entities[i].addTag('wither') 
                dimension.spawnItem(new ItemStack('edx:corrupted_star', 1), entities[i].location);
            }
        hitEntity.addTag('wither')
    }
    if (evd.damagingEntity.typeId === 'edx:burper' && (isFamily('mob', evd.hitEntity) === true)) {
        const mob = evd.hitEntity;
        let health = mob.getComponent("health")
        if (health.currentValue === 0) 
        {
                evd.damagingEntity.setDynamicProperty("mob_eat", evd?.damagingEntity?.getDynamicProperty("mob_eat")==undefined?1:evd?.damagingEntity?.getDynamicProperty("mob_eat")+1);
                evd.damagingEntity.dimension.playSound('mob.burper.burp',evd.damagingEntity.location,{pitch: 0.8 - evd.damagingEntity.getDynamicProperty("mob_eat")/100 ,});
                evd.damagingEntity.addEffect('regeneration', 320, {amplifier: 1})
            if ((isFamily('burper0', evd.damagingEntity) === true) && evd.damagingEntity.getDynamicProperty("mob_eat")==1) {
                evd.damagingEntity.triggerEvent("edx:burper1");
                world.getDimension(evd.damagingEntity.dimension.id).spawnParticle('edx:burper_grow',evd.damagingEntity.getHeadLocation());
                evd.damagingEntity.dimension.playSound('mob.burper.grow',evd.damagingEntity.location,{pitch: 0.8 - evd.damagingEntity.getDynamicProperty("mob_eat")/100 ,});
            } 
            if ((isFamily('burper1', evd.damagingEntity) === true) && evd.damagingEntity.getDynamicProperty("mob_eat")==3) {
                evd.damagingEntity.triggerEvent("edx:burper2");
                world.getDimension(evd.damagingEntity.dimension.id).spawnParticle('edx:burper_grow',evd.damagingEntity.getHeadLocation());
                evd.damagingEntity.dimension.playSound('mob.burper.grow',evd.damagingEntity.location,{pitch: 0.8 - evd.damagingEntity.getDynamicProperty("mob_eat")/100 ,});
            }
            if ((isFamily('burper2', evd.damagingEntity) === true) && evd.damagingEntity.getDynamicProperty("mob_eat")==6) {
                evd.damagingEntity.triggerEvent("edx:burper3");
                world.getDimension(evd.damagingEntity.dimension.id).spawnParticle('edx:burper_grow',evd.damagingEntity.getHeadLocation());
                evd.damagingEntity.dimension.playSound('mob.burper.grow',evd.damagingEntity.location,{pitch: 0.8 - evd.damagingEntity.getDynamicProperty("mob_eat")/100 ,});
            }
            if ((isFamily('burper3', evd.damagingEntity) === true) && evd.damagingEntity.getDynamicProperty("mob_eat")==10) {
                evd.damagingEntity.triggerEvent("edx:burper4");
                world.getDimension(evd.damagingEntity.dimension.id).spawnParticle('edx:burper_grow',evd.damagingEntity.getHeadLocation());
                evd.damagingEntity.dimension.playSound('mob.burper.grow',evd.damagingEntity.location,{pitch: 0.8 - evd.damagingEntity.getDynamicProperty("mob_eat")/100 ,});
            }
            if ((isFamily('burper4', evd.damagingEntity) === true) && evd.damagingEntity.getDynamicProperty("mob_eat")==15) {
                evd.damagingEntity.triggerEvent("edx:burper5");
                world.getDimension(evd.damagingEntity.dimension.id).spawnParticle('edx:burper_grow',evd.damagingEntity.getHeadLocation());
                evd.damagingEntity.dimension.playSound('mob.burper.grow',evd.damagingEntity.location,{pitch: 0.8 - evd.damagingEntity.getDynamicProperty("mob_eat")/100 ,});
            }
            if ((isFamily('burper5', evd.damagingEntity) === true) && evd.damagingEntity.getDynamicProperty("mob_eat")==21) {
                evd.damagingEntity.triggerEvent("edx:burper6");
                world.getDimension(evd.damagingEntity.dimension.id).spawnParticle('edx:burper_grow',evd.damagingEntity.getHeadLocation());
                evd.damagingEntity.dimension.playSound('mob.burper.grow',evd.damagingEntity.location,{pitch: 0.8 - evd.damagingEntity.getDynamicProperty("mob_eat")/100 ,});
            }
            if ((isFamily('burper6', evd.damagingEntity) === true) && evd.damagingEntity.getDynamicProperty("mob_eat")==32) {
                world.getDimension(evd.damagingEntity.dimension.id).spawnParticle('edx:burper_grow',evd.damagingEntity.getHeadLocation());
                evd.damagingEntity.dimension.playSound('mob.burper.grow',evd.damagingEntity.location,{pitch: 0.8 - evd.damagingEntity.getDynamicProperty("mob_eat")/100 ,});
                const burper = entity.dimension.spawnEntity("edx:burper", entity.location);
                burper.triggerEvent('edx:entity_summoned')
                evd.damagingEntity.setDynamicProperty("mob_eat", 22) 
            }
        }
    }


});