import { world, system, EntityDamageCause, EquipmentSlot} from "@minecraft/server";
import { launchPlayer } from "../../util/movements.js";
import { weaponDamageIndicator, generateUniqueId, getAmmoCount} from "../../util/utils.js";
import { spawnProjectile, attackPlayerMeikyu } from "../../util/attackMethods.js";
import {JsonDatabase} from "../../util/con-database.js";

let AmmoBody = new JsonDatabase("ammo_handblaster")

export function getAmmounthand_blaster(player) {
    let aria = AmmoBody.get(player.id)
    return aria
}

export function setAmmounthand_blaster(player) {
    AmmoBody.set(player.id, {
        stone:0,
        blackstone:0,
        cobblestone:0
    })
}



function reloaded(player,ticks,ammo,ammount) {
    let al = system.runTimeout(()=>{
        let count = 0
        for(let ammu = 0;ammu < ammo.length; ammu++){
            let amm = AmmoBody.get(player.id)
            let TheKey = Object.keys(amm)
            if(count < ammount) {
                let Dracula = AmmoBody.get(player.id)
                let enough = getAmmoCount(player,ammo[ammu])
                if(enough > 0 && enough >= (ammount - count)) {
                    player.runCommand(`clear @s ${ammo[ammu]} 0 ${ammount - count}`)
                    console.warn(count)
                    Dracula[TheKey[ammu]] = ammount - count
                    count = count + (ammount - count)
                    AmmoBody.set(player.id, Dracula)
                } else if(enough > 0 && enough < ammount && count <= 0) {
                    player.runCommand(`clear @s ${ammo[ammu]} 0 ${enough}`)
                    Dracula[TheKey[ammu]] = enough
                    count = count + (enough)
                    AmmoBody.set(player.id, Dracula)
                } else if(enough > 0 && enough >= ammount && (enough - count) <= 20) {
                    player.runCommand(`clear @s ${ammo[ammu]} 0 ${ammount}`)
                    Dracula[TheKey[ammu]] = ammount
                    count = count + (ammount)
                    AmmoBody.set(player.id, Dracula)
                }
                
            }
        }
        if(count == 0) {
            player.runCommand(`say not enough ammunitions`)
        }
        player.setDynamicProperty("attacking",0)
        world.scoreboard.getObjective("combatCooldown").setScore(player, 10)
        world.scoreboard.getObjective("combatCheck").setScore(player, 0)
        player.runCommandAsync("tag @s remove attack")
    },ticks)
}

const animations =[
    [
        {
            animation: "minced.hand_cannon.attack_sprint",
            knockback: [0,0],
            Player_Knockback: [2,0],
            type: "slash",
            attack_speed: 10,
            hit_number: 1,
            stun_type: "long",
            range: 3,
            distance: 2,
            targetNum: 1,
            damage_multiplier: 1,
            stun_damage_multiplier: 1,
            next_attack_time: 5,
            Unbreakable: false
        },
        {
            animation: "minced.hand_cannon.attack0",
            knockback: [5,0.25],
            Player_Knockback: [1,0.25],
            type: "blunt",
            attack_speed: 13,
            hit_number: 1,
            stun_type: "long",
            range: 3,
            distance: 2,
            targetNum: 10,
            damage_multiplier: 1,
            stun_damage_multiplier: 3,
            next_attack_time: 5,
            Unbreakable: false
        },
        {
            animation: "minced.hand_cannon.attack1",
            knockback: [5,0.25],
            Player_Knockback: [1,0.25],
            type: "blunt",
            attack_speed: 12,
            hit_number: 1,
            stun_type: "long",
            range: 3,
            distance: 2,
            targetNum: 1,
            damage_multiplier: 1,
            stun_damage_multiplier: 2,
            next_attack_time: 5,
            Unbreakable: false
        }
    ]
]

const weapon = {
    name: 'hand_cannon',
    display_name: "Hand_Cannon",
    ammount: 20,
    dual_wield: ["greatsword","longsword","katana","wakizashi","odachi","pistol"],
    type: "shooter",
    can_block: false,
    bulletTypes: ["minecraft:stone","minecraft:blackstone","minecraft:cobblestone"],
    block_damage: 33,
    front_dodge: [3, 2],
    block_time: 6,
    clash_power: 20,
    back_dodge:[-3, 1],
    left_dodge:[3, 0.2],
    right_dodge:[3, 0.2],
    stylePrefixes: ["minced.hand_cannon"],
    available_moves: ["front_dodge","back_dodge"],
    weaponSize: "large",
    cd: 20,
    execute(player, weapon, effect, mode, burn) {
        const blckdmg = this.block_damage
        const cd = this.cd
        let atkspd
        let animChecker
        for(let i = (animations[0].length - 1); i > 0; i--) {
            if(player.getDynamicProperty("combo") % i == 0) {
                animChecker = i
                break;
            }
        }
        let amm = AmmoBody.get(player.id)
        let AmmCoun = 0
        let TheKey = Object.keys(amm)
        console.warn(JSON.stringify(TheKey))
        for (let key = 0;key < TheKey.length; key++) {
            AmmCoun = AmmCoun + amm[TheKey[key]];
            console.warn(`ammo = ${amm[TheKey[key]]}`)
        }
        console.warn(AmmCoun)
        let lavander = weaponDamageIndicator(weapon)
        let attackEffect = []
        attackEffect.push(effect)
        switch(mode) {
            case "front_dodge":{
                if(AmmCoun >= 0) {
                    console.warn("play")
                    player.playAnimation(`animation.minced.hand_cannon.attack_forward`, 
                    {
                        blendOutTime: 0.1,
                        stopExpression: "query.all_animations_finished && query.is_on_ground",
                        nextState: `animation.minced.hand_cannon.combat_stance`
                    })
                    system.runTimeout(() =>{
                        player.runCommand("teleport @s ~~~ facing @e[type=!player,type=!pixel:hit_box,type=!minced:middle_entity,type=!item,c=1,r=10]")
                    },2);
                    system.runTimeout(() =>{
                        for(let i = 1; i <= 3; i++) {
                            spawnProjectile(player, `pixel:hand_cannon_bullet<minecraft:stone>`, 1, 0, 10, "normal", "",10, 1, 30, 1, 1, 1, "line_target", attackEffect, [1, 2], "short", "", "blunt", 10, "normal", 1)
                            player.runCommand(`execute as @s run camerashake add @s 0.3 0.3`)
                        } 
                        launchPlayer(player, 3, 1.5)
                        player.triggerEvent("Iframe")
                        
                    },4);
                    system.runTimeout(() =>{
                        player.setDynamicProperty("attacking",0)
                        world.scoreboard.getObjective("combatCooldown").setScore(player, 10)
                        world.scoreboard.getObjective("combatCheck").setScore(player, 0)
                        player.runCommandAsync("tag @s remove attack")
                        player.addEffect("slow_falling", 40, { amplifier: 3, showParticles: false })
                    },6);
                    system.runTimeout(() =>{
                        launchPlayer(player, 3, -0.6)
                        player.runCommand(`execute as @s run camerashake add @s 0.5 0.3`)
                    },14);
                    system.runTimeout(() =>{
                        player.triggerEvent("Iframe_remove")
                    },20);
                    
                } 
            }
                
            break;
            case "back_dodge":{
                console.warn("player")
                if(AmmCoun >= 0) {
                    console.warn("play")
                    player.playAnimation(`animation.minced.hand_cannon.attack_backward`, 
                    {
                        blendOutTime: 0.1,
                        stopExpression: "query.all_animations_finished && query.is_on_ground",
                        nextState: `animation.minced.hand_cannon.combat_stance`
                    })
                    system.runTimeout(() =>{
                        spawnProjectile(player, `pixel:hand_cannon_bullet<minecraft:stone>`, 1, 1, 10, "normal", "",10, 1, 30, 1, 1, 1, "line_target", attackEffect, [1, 2], "short", "", "blunt", 10, "normal", 1) 
                        launchPlayer(player, -3, 0.5)
                        player.runCommand(`execute as @s run camerashake add @s 0.3 0.3`)
                    },4);
                    system.runTimeout(() =>{
                        player.setDynamicProperty("attacking",0)
                        world.scoreboard.getObjective("combatCooldown").setScore(player, 10)
                        world.scoreboard.getObjective("combatCheck").setScore(player, 0)
                        player.runCommandAsync("tag @s remove attack")
                        player.addEffect("slow_falling", 5, { amplifier: 3, showParticles: false })
                    },6);
                    
                } else if(AmmCoun < 0){
                    reloaded(player,10,"minecraft:stone", this.ammount)
                }
            } break;
            case "on_air_combo": {
                if(AmmCoun >= 0) {
                    console.warn("play")
                    player.playAnimation(`animation.minced.hand_cannon.attack_forward`, 
                    {
                        blendOutTime: 0.1,
                        stopExpression: "query.all_animations_finished && query.is_on_ground",
                        nextState: `animation.minced.hand_cannon.combat_stance`
                    })
                    system.runTimeout(() =>{
                        player.runCommand("teleport @s ~~~ facing @e[type=!player,type=!pixel:hit_box,type=!item,c=1,r=10]")
                    },2);
                    system.runTimeout(() =>{
                        for(let i = 1; i <= 3; i++) {
                            spawnProjectile(player, "pixel:flareball", 1, 0, 10, "normal", "",10, 1, 30, 1, 1, 1, "line_target", attackEffect, [1, 2], "short", "", "blunt", 10, "normal", 1)
                            player.runCommand(`execute as @s run camerashake add @s 0.3 0.3`)
                        } 
                        launchPlayer(player, 3, 1.5)
                        player.triggerEvent("Iframe")
                        
                    },4);
                    system.runTimeout(() =>{
                        player.setDynamicProperty("attacking",0)
                        world.scoreboard.getObjective("combatCooldown").setScore(player, 10)
                        world.scoreboard.getObjective("combatCheck").setScore(player, 0)
                        player.runCommandAsync("tag @s remove attack")
                        player.addEffect("slow_falling", 40, { amplifier: 3, showParticles: false })
                    },6);
                    system.runTimeout(() =>{
                        launchPlayer(player, 3, -0.6)
                        player.runCommand(`execute as @s run camerashake add @s 0.5 0.3`)
                    },14);
                    system.runTimeout(() =>{
                        player.triggerEvent("Iframe_remove")
                    },20);
                    
                } 
            } break;
            case "execute": {
                executer(player, burn, (lavander * 200), this.name, 44)
            } break;
            default:
                switch(burn) {
                    case  "": {
                        console.warn("player")
                        if(AmmCoun > 0) {
                            console.warn("play")
                            player.playAnimation(`animation.minced.hand_cannon.attack_stance`, 
                            {
                                blendOutTime: 0.1,
                                stopExpression: "query.all_animations_finished",
                                nextState: `animation.minced.hand_cannon.combat_stance`
                            })
                            system.runTimeout(() =>{
                                let AmmoType
                                for(let amyu = 0;amyu < this.bulletTypes.length; amyu++){
                                    let TheKey = Object.keys(amm)
                                    if(amm[TheKey[amyu]] > 0) {
                                        amm[TheKey[amyu]] = amm[TheKey[amyu]] - 1
                                        AmmoType = this.bulletTypes[amyu]
                                        AmmoBody.set(player.id, amm)
                                        break;
                                    }
                                }
                                spawnProjectile(player, `pixel:hand_cannon_bullet<${AmmoType}>`, 1, 1, 10, "normal", "", 10, 1, 30, 1, 1, 1, "line_target", attackEffect, [1, 2], "short", "", "blunt", 10, "normal", 1 )
                                launchPlayer(player, -1, 0)
                                console.warn("4444")
                            },9);
                            system.runTimeout(() =>{
                                player.setDynamicProperty("attacking",0)
                                world.scoreboard.getObjective("combatCooldown").setScore(player, 10)
                                world.scoreboard.getObjective("combatCheck").setScore(player, 0)
                                player.runCommandAsync("tag @s remove attack")
                            },19);
                            
                        } else if(AmmCoun == 0){
                            reloaded(player,10, this.bulletTypes, this.ammount)
                        }
                        
                    } break;
                    default: {
                        let stundamage = 10
                        let propCheck = animations[0][animChecker]
                        let knockback = propCheck.knockback
                        player.playAnimation(`animation.${propCheck.animation}`)
                        atkspd = propCheck.attack_speed
                        let Pknockback = propCheck.Player_Knockback
                        launchPlayer(player, Pknockback[0], Pknockback[1])
                        let effects = propCheck.type
                        let stun = propCheck.stun_type
                        let ranger = propCheck.range
                        let distil = propCheck.distance
                        let tgtnm = propCheck.targetNum
                        let NAT = propCheck.next_attack_time
                        let breakable = propCheck.Unbreakable
                        let hitCount = propCheck.hit_number
                        if(animChecker == 3) {
                            player.addEffect("slow_falling", 16, { amplifier: 3, showParticles: false })
                        }
                        attackPlayerMeikyu(player, ranger, (lavander * propCheck.damage_multiplier), blckdmg, cd, atkspd, distil, tgtnm, "line_target", attackEffect, knockback, stun, "", effects, (animations[0].length - 1), stundamage, NAT, breakable, "normal",weapon, hitCount, true)
                    }
                }
            
            break;
        }
        console.warn(AmmCoun)
    },
    setCore(player, item) {
        let Abilities = [
            {
              Id: "S1",
            },
            {
              Id: "P3",
            },
            {
              Id: "O0",
            },
            {
              Id: "C2",
            },
            {
              Id: "O0",
            }
          ]
          item.setDynamicProperty("abilities", JSON.stringify(Abilities))
          item.setDynamicProperty("fightStyle", 1)
        player.getComponent('equippable')?.setEquipment(EquipmentSlot.Mainhand, item)
    },
    getCurrentAtkspd(player) {
        let animChecker
        for(let i = (animations[0].length - 1); i > 0; i--) {
            if(player.getDynamicProperty("combo") % i == 0) {
                animChecker = i
                break;
            }
        }
        return animations[0][animChecker].attack_speed
    } 
}

export default weapon


