import * as mc from "@minecraft/server"
import { ItemSkills, itemStack, startAnimations } from "./item"
import { onDamageItem, onKillItem } from "./damager"

const playerItemState = new Map()
function updatePlayerItemState(player) {
    const item = player.getComponent(mc.EntityEquippableComponent.componentId)
        ?.getEquipment(mc.EquipmentSlot.Mainhand)
    const state = playerItemState.get(player)

    if (item?.typeId === itemStack.typeId) {
        if (!state || state.typeId !== item.typeId) {
            state?.itemSkills.after()
            const itemSkills = new ItemSkills(item, player)
            itemSkills.before()
            playerItemState.set(player, { itemSkills, typeId: item.typeId })
        } else {
            state.itemSkills.repeat()
        }
    } else if (state) {
        state.itemSkills.after()
        playerItemState.delete(player)
    }
}
mc.system.runInterval(() => {
    mc.world.getAllPlayers().forEach(updatePlayerItemState)
}, 1)

// damager tracker

mc.world.afterEvents.entityHurt.subscribe(data => {
    if (!data.damageSource.damagingEntity || data.damageSource.damagingEntity.typeId !== "minecraft:player") return
    const entity = data.hurtEntity,
    player = data.damageSource.damagingEntity,
    damage = data.damage
    
    /** @type { mc.EntityEquippableComponent } */
    const equippable = player.getComponent(mc.EntityEquippableComponent.componentId)
    const item = equippable.getEquipment(mc.EquipmentSlot.Mainhand)
    if (item?.typeId !== itemStack.typeId) return
    onDamageItem(player, entity)
})

mc.world.afterEvents.entityDie.subscribe(data => {
    if (!data.damageSource.damagingEntity || data.damageSource.damagingEntity?.typeId !== "minecraft:player") return
    const entity = data.deadEntity,
    player = data.damageSource.damagingEntity,
    damage = data.damage
    
    /** @type { mc.EntityEquippableComponent } */
    const equippable = player.getComponent(mc.EntityEquippableComponent.componentId)
    const item = equippable.getEquipment(mc.EquipmentSlot.Mainhand)
    if (item?.typeId !== itemStack.typeId) return
    onKillItem(player, entity)
})

mc.world.afterEvents.playerSpawn.subscribe(data => {
    const player = data.player
    const EntityEquippableComponent = player.getComponent(mc.EntityEquippableComponent.componentId)
    if (EntityEquippableComponent.getEquipment(mc.EquipmentSlot.Mainhand)?.typeId !== itemStack.typeId) return
    const tick = mc.system.runInterval(() => {
        try { player.applyKnockback(1, 1, 0.0001, 0.0001) } catch {}
        if (player.getVelocity().x  !== 0 || player.getVelocity().y  !== 0 || player.getVelocity().z  !== 0) {
            mc.system.clearRun(tick)
            startAnimations(player)
        }
    }, 1)
})

import "./ult"