import { world, system, EquipmentSlot, Player, ItemStack } from "@minecraft/server"

// ! Hurt Triggers
// ! Sneak Functions
world.afterEvents.playerButtonInput.subscribe(ev => {
    let player = ev.player
    let offhand = player.getComponent('equippable').getEquipment('Offhand') ?? undefined
    let mainhand = player.getComponent('equippable').getEquipment('Mainhand') ?? undefined

    // * Triox Gauntlets
    if (offhand?.typeId === 'darkw_dotv:charm_triox' && ev.button == 'Sneak' && ev.newButtonState == 'Pressed') {
        if (player.getItemCooldown('darkw_dotv:charm_triox') != 0) return
        player.playAnimation('animation.darkw_dotv-primordial_dubtrox.block_player')
        sneakTick()
        async function sneakTick() {
            while (player.isSneaking) {
                await system.waitTicks(18)
                if (!player.isSneaking) return
                player.addTag('darkw_dotv:is_triox_blocking')
                player.playAnimation('animation.darkw_dotv-primordial_dubtrox.block_player', {
                    stopExpression: '!query.is_sneaking'
                })
            }
        }

    }
    // * Legatus Blade
    if (offhand?.typeId === 'darkw_dotv:charm_legatus' && ev.button == 'Sneak' && ev.newButtonState == 'Pressed') {
        if (player.getItemCooldown('darkw_dotv:charm_legatus') != 0) return
        player.startItemCooldown('darkw_dotv:charm_legatus', 50)
        player.dimension.playSound('random.fuse', player.location)
        player.dimension.playSound('legatus.summon', player.location)

        let tick = 0
        onTimeout()
        async function onTimeout() {
            while (tick < 51 && player.isSneaking) {
                await system.waitTicks(1)
                player.dimension.spawnParticle('darkw_dotv:legatus_phasetwo_chargeup_sword', player.location)
                tick++
                if (tick == 50) {
                    player.dimension.playSound('random.explode', player.location)
                    player.dimension.createExplosion(player.location, 2, { breaksBlocks: false, source: player })
                    player.dimension.spawnParticle('darkw_dotv:legatus_shieldburst', player.location)
                    let d = offhand.getComponent('durability')
                    if (player.getGameMode() != 'Creative') {

                        let ranDam = 150
                        let item = offhand
                        if (d.damage + ranDam > d.maxDurability) {
                            player.runCommand('/playsound random.break @s ~ ~ ~')
                            player.getComponent('equippable').setEquipment(EquipmentSlot.Offhand, new ItemStack('air', 1))
                        }
                        else {
                            d.damage += ranDam
                            player.getComponent('equippable').setEquipment(EquipmentSlot.Offhand, item)
                        }
                    }
                }
            }
        }
    }
    // * YANG BLADE
    if (mainhand?.typeId === 'darkw_dotv:weapon_yang' && ev.button == 'Sneak' && ev.newButtonState == 'Pressed') {
        if (player.getItemCooldown('darkw_dotv:yang') != 0) return
        let voidheart = world.scoreboard.getObjective('darkw_dotv:DESTRUCTIONCAHRGE_dmg')
        player.startItemCooldown('darkw_dotv:yang', 100)
        let dur = parseInt(voidheart.getScore(player) / 2)
        player.dimension.spawnParticle('darkw_dotv:yangparticle_spray', player.location)
        player.runCommand('/playsound weapon.yang.boom @a ~~~ 1 1.75')
        player.runCommand('camerashake add @s 0.1 1 positional')
        player.dimension.getEntities({ location: player.location, maxDistance: 9 }).forEach(m => {
            if (m.nameTag != player.nameTag) {
                m.addEffect('wither', dur, { amplifier: 5 })
                voidheart.setScore(player, 0)
            }
        })
    }
})

world.afterEvents.entityHitEntity.subscribe(ev => {
    // If player attacks, do something
    if (!ev.damagingEntity) return
    if (!ev.damagingEntity instanceof Player) return

    let player = ev.damagingEntity
    if (!ev.hitEntity) return
    // Triox Charm

    try {
        if (ev.hitEntity) {
            if (!ev.hitEntity) return
            if (ev.hitEntity?.hasTag('darkw_dotv:is_triox_blocking')) {
                ev.damagingEntity.applyDamage(10, {
                    cause: 'entity_attack',
                    damagingProjectile: ev.damagingEntity,
                    damagingEntity: ev.damagingEntity
                })
                ev.hitEntity.startItemCooldown('darkw_dotv:charm_triox', 50)
                ev.hitEntity.removeTag('darkw_dotv:is_triox_blocking')
                let item = ev.hitEntity.getComponent('equippable').getEquipmentSlot('Offhand').getItem() ?? undefined
                let container = ev.hitEntity.getComponent('inventory').container
                let d = item?.getComponent('durability')
                if (!d) return
                let ranDam = Math.floor(Math.random() * 20)
        
                if (ev.hitEntity.getGameMode() != 'Creative') {
        
        
                    if (d.damage + ranDam > d.maxDurability) {
                        player.runCommand('/playsound random.break @s ~ ~ ~')
                        ev.hitEntity.getComponent('equippable').setEquipment(EquipmentSlot.Offhand, new ItemStack('air', 1))
                    }
                    else {
                        d.damage += ranDam
                        ev.hitEntity.getComponent('equippable').setEquipment(EquipmentSlot.Offhand, item)
                    }
                }
            }
            // Dance Charm
            if (player.runCommand('/testfor @s[hasitem={item=darkw_dotv:charm_dubtrox, location=slot.hotbar}]').successCount) {
                let ran = Math.floor(Math.random() * 10)
                let container = player.getComponent('inventory').container
                for (let s = 0; s != 9; s++) {
                    if (!container.getItem(s)) continue;
                    if (container.getItem(s)?.typeId === 'darkw_dotv:charm_dubtrox') {
                        let item = container.getItem(s)
                        let ran = Math.floor(Math.random() * 10)
                        let ranDam = Math.floor(Math.random() * 15)
                        let d = item.getComponent('durability')
                        let cool = item.getComponent('cooldown')
                        if (ran < 5 || cool.getCooldownTicksRemaining(player) > 0) return
        
                        let ranBuffList = [
                            "strength",
                            "speed",
                            "regeneration",
                            "resistance"
                        ]
                        let ranStr = ranBuffList[Math.floor(Math.random() * ranBuffList.length)]
                        player.addEffect(ranStr, 200, {
                            amplifier: 2,
                            showParticles: true
                        })
                        player.dimension.spawnParticle(`darkw_dotv:dubby-buff_${ranStr}`, { x: player.location.x, y: player.location.y, z: player.location.z })
        
                        item.getComponent('cooldown').startCooldown(player)
                        if (player.getGameMode() != 'Creative') {
        
                            if (d.damage + ranDam > d.maxDurability) {
                                player.runCommand('/playsound random.break @s ~ ~ ~')
                                container.setItem(s, new ItemStack('air', 1))
                            }
                            else {
                                d.damage += ranDam
                                container.setItem(s, item)
                            }
                        }
                        return
                    }
                }
            }
        }
    }
    catch {}
})