import * as mc from "@minecraft/server"
import * as lib from "../lib"
import { excludeFamilies, excludeTypes, runEntity } from "./utils"
import { ActionManager } from "../lib/actionManager"


const actionManager = new ActionManager();


const type = "ld_hw:the_corruptor";
let damageMultiplier = 3


const tick = mc.system.runInterval(() => {

    runEntity({ typeId: type }, 
        
        (entity) => {

            
            if (entity.getProperty("ld_hw:dying") === true) { 

                actionManager.stopAllActions(entity)  
                return; 


            }

            
            
            const health = entity.getComponent("minecraft:health")

            
            if (health.currentValue === 1 && entity.getProperty("ld_hw:delay") === false) {

                entity.triggerEvent("ld_hw:die")
                entity.setProperty("ld_hw:dying", true)  
                entity.setProperty("ld_hw:delay", true)  
                actionManager.stopAllActions(entity)  
                entity.runCommand(`loot spawn ~~~ loot "ld_hw/the_corruptor"`)
                if(mc.world.getDynamicProperty(`ld_hw.:sound`)==true) {
                    entity.runCommand(`stopsound @a[r=20] ld_hw:fight_song`)
                    entity.runCommand(`playsound ld_hw:effect.hit @a[r=20]`)
                }
                return;

            }

            
            if (entity.getProperty("ld_hw:near_target") === false || entity.getProperty("ld_hw:delay") === true) { return; }

            
            skillIds(entity)


        }
    )
    if(mc.world.getDynamicProperty('ld_hw.:difficulty')==0 && damageMultiplier!=2){
        damageMultiplier = 2
    } else if(mc.world.getDynamicProperty('ld_hw.:difficulty')==1 && damageMultiplier!=2.5){
        damageMultiplier = 2.5
    } else if(mc.world.getDynamicProperty('ld_hw.:difficulty')==2 && damageMultiplier!=3){
        damageMultiplier = 3
    }


}, 20 * 0.1)


function skillIds(entity) {
    let randomSkill = lib.calculate.random(0, 2)
    if (randomSkill === entity.getDynamicProperty("ld_hw:after_random_skill")) { return skillIds(entity) }
    skills[randomSkill](entity)
    entity.setDynamicProperty("ld_hw:after_random_skill", randomSkill)
}
const skills = [

    
    function(entity) {

        
        entity.setProperty("ld_hw:anim", 1)
        actionManager.createTimeout(entity, () => { entity.setProperty("ld_hw:anim", 0) }, 1)

        
        const movement = entity.getComponent("minecraft:movement")
        movement.setCurrentValue(0)

        const targets = entity.dimension.getEntities({
            location: entity.location,
            maxDistance: 8,
            excludeFamilies: excludeFamilies,
            excludeTypes: excludeTypes,
            excludeTypes: [entity.typeId]
        })
        targets.forEach(target => {
            if (target.typeId==='minecraft:player'){target.runCommand('camerashake add @s 0.10 4 positional')}
        })
        actionManager.createTimeout(entity, () => {

            
            targets.forEach(target => {
                if (!target.isValid()) return
                target.applyDamage(2 * damageMultiplier, { cause: "contact", damagingEntity: entity })
                target.addEffect('slowness', 3, {amplifier: 2})
                if (target.typeId==='minecraft:player'){target.runCommand('camerashake add @s 0.10 3 positional')}
            })

            const glitchAttack = entity.dimension.spawnEntity('ld_hw:glitch_attack', entity.location)
            const interval = mc.system.runInterval(()=>{
                if (!glitchAttack.isValid()) return
                glitchAttack.runCommand(`spreadplayers ${entity.location.x} ${entity.location.z} 2 10 @s`);
                const block = entity.dimension.getBlock({x:glitchAttack.location.x,y:glitchAttack.location.y-2,z:glitchAttack.location.z});
                let blockId = block.typeId;
                const randHeight = Math.random(-2,2)
                glitchAttack.dimension.spawnParticle('ld_hw:virus_spread_10', glitchAttack.location)
                glitchAttack.runCommand(`setblock ~~-2~ air`)
                glitchAttack.runCommand(`setblock ~~${randHeight}~ ${blockId}`)
                glitchAttack.runCommand(`playsound ld_hw:effect.glitch @a ~~~`)
            })
            const entityDestroying = mc.system.runInterval(()=>{
                entity.runCommand(`fill ~-1~~-1 ~1~4~1 air`)
            })
            mc.system.runTimeout(()=>{
                mc.system.clearRun(entityDestroying)
            },10*20)
            
            entity.setProperty("ld_hw:delay", true)
            actionManager.createTimeout(entity, () => {

                entity.triggerEvent("ld_hw:remove_attack")
                actionManager.stopAllActions(entity)  


            }, 20 * 2)


        }, 20 * 0.5)


    },

    
    function(entity) {

        
        entity.setProperty("ld_hw:anim", 2)
        actionManager.createTimeout(entity, () => { entity.setProperty("ld_hw:anim", 0) }, 1)

        
        const movement = entity.getComponent("minecraft:movement")
        movement.setCurrentValue(0)

        
        actionManager.createTimeout(entity, () => {

            const targets = entity.dimension.getEntities({
                location: entity.location,
                maxDistance: 5,
                excludeFamilies: excludeFamilies,
                excludeTypes: excludeTypes,
                excludeTypes: [entity.typeId]
            })

            
            targets.forEach(target => {
                target.applyDamage(2 * damageMultiplier, { cause: "contact", damagingEntity: entity })
                target.addEffect('slowness', 60, {amplifier: 5})
                if (target.typeId==='minecraft:player'){target.runCommand('camerashake add @s 0.10 4 positional')}
            })
            
            entity.setProperty("ld_hw:delay", true)
            actionManager.createTimeout(entity, () => {

                entity.triggerEvent("ld_hw:remove_attack")


            }, 20 * 1)


        }, 20 * 0.5)


    },

    
    function(entity) { 
        const movement = entity.getComponent("minecraft:movement")
        movement.setCurrentValue(0)
        entity.setProperty("ld_hw:delay", true)
        const loopTime = [
            1,4,7
        ]
        const targets = entity.dimension.getEntities({
            location: entity.location,
            maxDistance: 5,
            excludeFamilies: excludeFamilies,
            excludeTypes: excludeTypes,
            excludeTypes: [entity.typeId]
        })
        targets.forEach(target=>{
            if (!target.isValid()) return
            loopTime.forEach(time=>{
                mc.system.runTimeout(()=>{
                    entity.setProperty("ld_hw:anim", 3)
                    actionManager.createTimeout(entity, () => { entity.setProperty("ld_hw:anim", 0) }, 1)
                    mc.system.runTimeout(()=>{
                        if(!target.isValid()) return
                        entity.runCommand(`spreadplayers ${target.location.x} ${target.location.z} 1 5 @s`)
                    },0.75*20)
                    mc.system.runTimeout(()=>{
                        if(!target.isValid()) return
                        try {
                        target.applyDamage(2 * damageMultiplier, { cause: "contact", damagingEntity: entity })
                        target.applyKnockback(entity.getViewDirection().x,entity.getViewDirection().z,1, 1)
                        } catch (error) {
                            
                        }
                    },1.21*20)
                },time*20)
            })
        })
        actionManager.createTimeout(entity, () => {
            entity.triggerEvent("ld_hw:remove_attack")
            actionManager.stopAllActions(entity) 
        }, 20 * 8)
    }
]