import { world, system, EquipmentSlot, ItemStack} from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { weaponTypeSplicer, getAmmoCount } from "./utils.js";
import {JsonDatabase} from "./con-database.js";
import abilities from './../abilities/import.js';

let clashing = new JsonDatabase("clashing")
let inClash = new JsonDatabase("inClash")
let selectedSlot = new JsonDatabase("selectedSlot")
let entityStatus = new JsonDatabase("entityStatus")
let worldStatus = new JsonDatabase("worldStatus")

let stunnedScores = world.scoreboard.getObjective("stunned")
let stunBreakScores = world.scoreboard.getObjective("stunbreak")
let stunTimerScores = world.scoreboard.getObjective("stunTimer")
let stunCheckScores = world.scoreboard.getObjective("stunCheck")

function resetPlayer(player,playerName) {
    player.runCommand(`tag ${playerName} remove joyloy`)
}

function abilityTrigger(player, trigger, weapon, type) {
    let attackCheckers = true
    console.warn(trigger)
    stunnedScores.getScore(player) != 1 && stunBreakScores.getScore(player) != 1 && player.getDynamicProperty("attacking") != 1 ? attackCheckers = true : attackCheckers = false 
    if(trigger != "O0" && attackCheckers == true && JSON.parse(player.getDynamicProperty("entityStatus")).abilityCd[abilities[trigger].name] == undefined){
        let weaponType = weaponTypeSplicer(weapon)
        player.addTag("attack")
	    abilities[trigger].execute(player, weaponType, type);
	}
}

export function adminOptions(player) {
    let worldData = worldStatus.get("worldData")
    const fades =
        new ModalFormData()
            .title('Admin Options')
            .toggle("Super Jump", worldData.superJump)
            .toggle("Camera Shake", worldData.cameraShake)
            .toggle("Ability System", worldData.abilitySystem)
            .textField("Reset Player", "player name")
            .show(player)
            .then(result => {
                let NewActions = result.formValues
                worldData["superJump"] = NewActions[0]
                worldData["cameraShake"] = NewActions[1]
                worldData["abilitySystem"] = NewActions[2]
                worldStatus.set("worldData", worldData)
                resetPlayer(player,NewActions[3])
        })
}

export function attackForm(player) {
    const fades =
        new ActionFormData()
            .title('Attack')
            .body('')
            .button(`1`)
            .button(`2`)
            .show(player)
            .then(result => {
            if (result.selection === 0) {
                player.runCommand("execute as @s run scriptevent cmbt:listener attack")
                attackForm(player)
            }
            if (result.selection === 1) {
                player.runCommand("execute as @s run scriptevent cmbt:listener block")
                attackForm(player)
            }
        })
}

export function ability_writing(player, item) {
    let Newfades = world.scoreboard
    const fades =
        new ActionFormData()
            .title('MC:Ability_Write')
            .body('')
            .button(`Slash`)
            .button(`Air Slashes`)
            .button(`Shear`)
            .button(`Stone Cutter`)
            .button(`Iron Cutter`)

            .button(`Pierce`)
            .button(`Vorpal Strike`)
            .button(`Thrust`)
            .button(`Throw`)
            .button(`Stab`)

            .button(`Vibration Blitz`)
            .button(`Battle Cry`)
            .button(`Smash`)
            .button(`Uppercut`)
            .button(`Ram`)

            .button(`Accelerate`)
            .button(`Sheathe`)
            .button(`Pull`)
            .button(`Guard`)
            .button(`Counter`)

            .button(`Tip`)
            .button(`Taunt`)
            .button(`Rapid Fire`)
            .button(`Blaze Up`)
            .button(`Ram`)
            .show(player)
            .then(result => {
                let abili ="O0"
                if (result.selection === 0) {
                    abili = "S1"
                    player.onScreenDisplay.setActionBar(`Slash ability applied`)
                }
                if (result.selection === 1) {
                    if(Newfades.getObjective("slashing").getScore(player) > 0) {
                        abili = "A3"
                        player.onScreenDisplay.setActionBar(`Air Slash ability applied`)
                    } else {
                        player.onScreenDisplay.setActionBar(`Slashing skill not learned`)
                    }   
                }
                if (result.selection === 2) {
                    if(Newfades.getObjective("slashing").getScore(player) > 0) {
                        abili = "S4"
                        player.onScreenDisplay.setActionBar(`Shear ability applied`)
                    } else {
                        player.onScreenDisplay.setActionBar(`Slashing skill not learned`)
                    }   
                }
                if (result.selection === 3) {
                    if(Newfades.getObjective("cutting").getScore(player) > 0) {
                        abili = "S7"
                        player.onScreenDisplay.setActionBar(`Stone Cutter ability applied`)
                    } else {
                        player.onScreenDisplay.setActionBar(`Cutting skill not learned`)
                    }   
                }
                if (result.selection === 4) {
                    if(Newfades.getObjective("cutting").getScore(player) > 0) {
                        abili = "I2"
                        player.onScreenDisplay.setActionBar(`Iron Cutter ability applied`)
                    } else {
                        player.onScreenDisplay.setActionBar(`Cutting skill not learned`)
                    }   
                }
                if (result.selection === 5) {
                    abili = "P1"
                    player.onScreenDisplay.setActionBar(`Pierce ability applied`)
                }
                if (result.selection === 6) {
                    abili = "V1"
                    player.onScreenDisplay.setActionBar(`Vorpal Strike ability applied`)
                }
                if (result.selection === 7) {
                    abili = "T1"
                    player.onScreenDisplay.setActionBar(`Thrust ability applied`)
                }
                if (result.selection === 8) {
                    abili = "T2"
                    player.onScreenDisplay.setActionBar(`Throw ability applied`)
                }
                if (result.selection === 9) {
                    abili = "S3"
                    player.onScreenDisplay.setActionBar(`Stab ability applied`)
                }

                if (result.selection === 10) {
                    abili = "V2"
                    player.onScreenDisplay.setActionBar(`Vibration Blitz ability applied`)
                }
                if (result.selection === 11) {
                    abili = "B1"
                    player.onScreenDisplay.setActionBar(`Battle Cry ability applied`)
                }
                if (result.selection === 12) {
                    abili = "S8"
                    player.onScreenDisplay.setActionBar(`Smash ability applied`)
                }
                if (result.selection === 13) {
                    abili = "U1"
                    player.onScreenDisplay.setActionBar(`Uppercut ability applied`)
                }
                if (result.selection === 14) {
                    abili = "R2"
                    player.onScreenDisplay.setActionBar(`Ram ability applied`)
                }
                if (result.selection === 15) {
                    if(Newfades.getObjective("movement").getScore(player) > 0) {
                        abili = "A2"
                        player.onScreenDisplay.setActionBar(`Accelerate ability applied`)
                    } else {
                        player.onScreenDisplay.setActionBar(`Movement skill not learned`)
                    }
                }
                if (result.selection === 16) {
                    if(Newfades.getObjective("movement").getScore(player) > 0) {
                        abili = "S6"
                        player.onScreenDisplay.setActionBar(`Sheathe ability applied`)
                    } else {
                        player.onScreenDisplay.setActionBar(`Movement skill not learned`)
                    }
                }
                if (result.selection === 17) {
                    if(Newfades.getObjective("movement").getScore(player) > 0) {
                        abili = "P4"
                        player.onScreenDisplay.setActionBar(`Pull ability applied`)
                    } else {
                        player.onScreenDisplay.setActionBar(`Movement skill not learned`)
                    }
                }
                if (result.selection === 18) {
                    abili = "G1"
                    player.onScreenDisplay.setActionBar(`Guard ability applied`)
                }
                if (result.selection === 19) {
                    abili = "C1"
                    player.onScreenDisplay.setActionBar(`Counter ability applied`)
                }
                if (result.selection === 20) {
                    abili = "T3"
                    player.onScreenDisplay.setActionBar(`Tip ability applied`)
                }
                if (result.selection === 21) {
                    abili = "T4"
                    player.onScreenDisplay.setActionBar(`Taunt ability applied`)
                }
                if (result.selection === 22) {
                    abili = "R1"
                    player.onScreenDisplay.setActionBar(`Rapid Fire ability applied`)
                }
                if (result.selection === 23) {
                    abili = "B2"
                    player.onScreenDisplay.setActionBar(`Blaze Up ability applied`)
                }
                if (result.selection === 24) {
                    abili = "R2"
                    player.onScreenDisplay.setActionBar(`Ram ability applied`)
                }
                item.setLore([`${abili}`, `§6${JSON.stringify(abilities[abili].filters)}`])
                player.getComponent('equippable')?.setEquipment(EquipmentSlot.Mainhand, item)
            })
} 

export function pellet_container(player, item) {
    const fades =
        new ActionFormData()
            .title('Attack')
            .body('')
            .button(`Normal Bullet`)
            .button(`Fire Bullet`)
            .button(`Poison Bullet`)
            .show(player)
            .then(result => {
            let bullets = JSON.parse(item.getDynamicProperty("ammo"))
            let limit = JSON.parse(item.getDynamicProperty("abilities"))
            let count = bullets.length
            if(count >= limit) {
                player.onScreenDisplay.setActionBar(`Container Full`)
                return;
            }
            if (result.selection === 0) {
                let enough = getAmmoCount(player, "minced:bullet_normal")
                if(enough > 0) {
                    bullets.push("bn")
                    player.runCommand(`clear @s minced:bullet_normal 0 1`)
                    pellet_container(player, item)
                } else {
                    player.onScreenDisplay.setActionBar(`Not Enough Normal bullets`)
                }
            }
            if (result.selection === 1) {
                let enough = getAmmoCount(player, "minced:bullet_fire")
                if(enough > 0) {
                    bullets.push("bf")
                    player.runCommand(`clear @s minced:bullet_fire 0 1`)
                    pellet_container(player, item)
                } else {
                    player.onScreenDisplay.setActionBar(`Not Enough Fire bullets`)
                }
            }
            if (result.selection === 2) {
                let enough = getAmmoCount(player, "minced:bullet_poison")
                if(enough > 0) {
                    bullets.push("bp")
                    player.runCommand(`clear @s minced:bullet_poison 0 1`)
                    pellet_container(player, item)
                } else {
                    player.onScreenDisplay.setActionBar(`Not Enough Poison bullets`)
                }
            }
            item.setDynamicProperty("ammo", JSON.stringify(bullets))
            player.getComponent('minecraft:equippable').setEquipment(EquipmentSlot.Mainhand, item)
        })
}

export function styleChooser(player) {
    let item = player.getComponent("minecraft:equippable")?.getEquipment(EquipmentSlot.Mainhand)
    const fades =
        new ActionFormData()
            .title('MC:Style Chooser')
            .body('')
            .button(`Normal`)
            .button(`Strenght Style`)
            .show(player)
            .then(result => {
                if (result.selection === 0) {
                    item.setDynamicProperty("fightStyle", 0)
                }
                if (result.selection === 1) {
                    item.setDynamicProperty("fightStyle", 1)
                }
                player.getComponent("minecraft:equippable").setEquipment(EquipmentSlot.Mainhand, item)
        })
}

export function darkSoulsForm(player) {
    let equipment = player.getComponent("minecraft:equippable");
    let inventory = player.getComponent("minecraft:inventory").container
    const fades =
        new ActionFormData()
            .title('DsMenu')
            .body('')
            .button(`1`,`textures/items/${inventory.getItem(0).typeId.split(":")[1]}`)
            .button(`2`,`textures/items/${inventory.getItem(1).typeId.split(":")[1]}`)
            .button(`3`,`textures/items/${inventory.getItem(2).typeId.split(":")[1]}`)
            .button(`4`,`textures/items/${inventory.getItem(3).typeId.split(":")[1]}`)
            .show(player)
            .then(result => {
                if (result.selection === 0) {
                    player.selectedSlotIndex = 0
                    inventory.setItem(0, inventory.getItem(9))
                    inventory.setItem(9, inventory.getItem(18))
                    inventory.setItem(18, inventory.getItem(27))
                    inventory.setItem(27, inventory.getItem(0))
                    darkSoulsForm(player)
                }
                if (result.selection === 1) {
                    inventory.setItem(10, inventory.getItem(19))
                    inventory.setItem(19, inventory.getItem(28))
                    inventory.setItem(28, equipment?.getEquipmentSlot(EquipmentSlot.Offhand))
                    let offhand = equipment?.setEquipment(EquipmentSlot.Offhand, inventory?.getItem(19))
                    darkSoulsForm(player)
                }
                if (result.selection === 2) {
                    inventory.setItem(2, inventory.getItem(11))
                    inventory.setItem(11, inventory.getItem(20))
                    inventory.setItem(20, inventory.getItem(29))
                    inventory.setItem(29, inventory.getItem(2))
                    darkSoulsForm(player)
                }
                if (result.selection === 3) {
                    inventory.setItem(3, inventory.getItem(12))
                    inventory.setItem(12, inventory.getItem(21))
                    inventory.setItem(21, inventory.getItem(30))
                    inventory.setItem(30, inventory.getItem(3))
                    darkSoulsForm(player)
                }
                
        })
}

export function clashForm(player) {
    const fades =
        new ActionFormData()
            .title('clash')
            .body('')
            .button(`1`)
            .show(player)
            .then(result => {
            if (result.selection === 0) {
                let value = clashing.get(player.id)
                let inClashing = inClash.get(player.id)
                clashing.set(player.id,(value + 1))
                if(inClashing == 1) {
                    clashForm(player)
                }
            }
        })
}

export function abilityForm(player, item) {
    let ability = JSON.parse(item.getDynamicProperty("abilities"))
    let weaponclass = weaponTypeSplicer(item)
    const fade = new ActionFormData()
        .title('MC:ability_selector')
        .body('')
        .button(`first_button`,`${abilities[ability[0].Id].button_icon}`)
        .button(`second_button`,`${abilities[ability[1].Id].button_icon}`)
        .button(`third_button`,`${abilities[ability[2].Id].button_icon}`)
        .button(`Close Abiltiies Form`)
        .show(player)
        .then(result => {
        if (result.selection === 0) {
            selectedSlot.set(player.id,"return")
            abilityTrigger(player, ability[0].Id, item, "normal")
            player.runCommand(`dialogue open @e[type=minced:middle_entity,c=1] @s ability:xb`)
        }
        if (result.selection === 1) {
            selectedSlot.set(player.id,"return")
            player.runCommand(`dialogue open @e[type=minced:middle_entity,c=1] @s ability:xb`)
        }
        if (result.selection === 2) {
            selectedSlot.set(player.id,"return")
            abilityTrigger(player, ability[2].Id, item, "normal")
            player.runCommand(`dialogue open @e[type=minced:middle_entity,c=1] @s ability:xb`)
        }
        if (result.selection === 3) {
            console.warn("pressed")
            selectedSlot.set(player.id,"")
        }
        
    })
}

export function abilityFormDual(player, item) {
    let ability = JSON.parse(item.getDynamicProperty("abilities"))
    let weaponclass = weaponTypeSplicer(item)
    console.warn(weaponclass)
    const fade = new ActionFormData()
        .title('Dual Wield')
        .body('')
        .button(`first_button`,abilities[ability[0].Id].button_icon)
        .button(`second_button`,abilities[ability[1].Id].button_icon)
        .button(`third_button`,abilities[ability[2].Id].button_icon)
        .button(`Cancel`)
        .button(`dual_switch`)
        .show(player)
        .then(result => {
        if (result.selection === 0) {
            selectedSlot.set(player.id,"return")
            abilityFormDual(player, item)
            abilityTrigger(player, ability[0].Id, item, "normal")
            console.warn(selectedSlot.get(player.id))
        }
        if (result.selection === 1) {
            selectedSlot.set(player.id,"return")
            abilityFormDual(player, item)
            abilityTrigger(player, ability[1].Id, item, "normal")
            console.warn(selectedSlot.get(player.id))
        }
        if (result.selection === 2) {
            selectedSlot.set(player.id,"return")
            abilityFormDual(player, item)
            abilityTrigger(player, ability[2].Id, item, "normal")
            console.warn(selectedSlot.get(player.id))
        }
        if (result.selection === 3) {
            console.warn("pressed")
        }
        if (result.selection === 4) {
            console.warn("pressed")
            let dualwield = entityStatus.get(player.id)
            if(dualwield["dualwieldCheck"] == "offhand") {
                dualwield["dualwieldCheck"] = "dual_wield"
            } else if(dualwield["dualwieldCheck"] == "dual_wield") {
                dualwield["dualwieldCheck"] = "offhand"
            }
            console.warn(JSON.stringify(dualwield))
            entityStatus.set(player.id,dualwield)
            abilityFormDual(player, item)
        }
    })
}

export function DelayedSelector(player) {
    let usedDevice = player.clientSystemInfo.platformType
    switch(usedDevice) {
        case "Desktop": {
            world.scoreboard.getObjective("controls").setScore(player,2)
        } break;
        case "Console": {
            world.scoreboard.getObjective("controls").setScore(player,3)
        } break;
        case "Mobile": {
            world.scoreboard.getObjective("controls").setScore(player,1)
        } break;
    }
}


export function bladeSelector(player, item) {
    let BladeSelector =
        new ActionFormData()
        .title('Selector')
        .body('')
        .button(`Blade`)
        .button(`Handle`)
        .button(`Guard`)
        .button(`Pommel`)
        .button(`Fling`)
        .button(`Sheath`)
        .button(`Sheath Style`)
        .button(`Cancel`)
        .button(`Confirm`)
        .button(`0`)
        .button(`1`)
        .button(`2`)
        .button(`3`)
        .button(`4`)
        .button(`5`)
        .button(`6`)
        .button(`7`)
        .button(`8`)
        .show(player)
        .then(result => {
        if (result.selection === 0) {
            bladeSelector(player)
        }
        if (result.selection === 1) {
            handleSelector(player)
        }
        if (result.selection === 2) {
            guardSelector(player)
        }
        if (result.selection === 3) {
            pommelSelector(player)
        }
        if (result.selection === 4) {
            flingSelector(player)
        }
        if (result.selection === 5) {
            sheathSelector(player)
        }
        if (result.selection === 6) {
            sheathStyleSelector(player)
        }
        if (result.selection === 7) {
            Confirm(player)
        }
        if (result.selection === 8) {
            if(item.getLore() != "" && item.getLore()[0].includes("|") && item.getLore()[0].includes("¡")) {

                let just = item.getLore()[0].split('|')
                let part = just[2].split('P')
                let no = [`${just[0]}|${just[1]}|P1P${part[2]}P${part[3]}P${part[4]}P${part[5]}P${part[6]}P${part[7]}P${part[8]}|`,item.getLore()[1]]
                item.setLore(no)
                player.getComponent('equippable')?.setEquipment(EquipmentSlot.Mainhand, item)
            }
        }
        if (result.selection === 9) {
            if(item.getLore() != "" && item.getLore()[0].includes("|") && item.getLore()[0].includes("¡")) {
                let just = item.getLore()[0].split('|')
                let part = just[2].split('P')
                let no = [`${just[0]}|${just[1]}|P2P${part[2]}P${part[3]}P${part[4]}P${part[5]}P${part[6]}P${part[7]}P${part[8]}|`,item.getLore()[1]]
                item.setLore(no)
                player.getComponent('equippable')?.setEquipment(EquipmentSlot.Mainhand, item)
            }
        }
        if (result.selection === 10) {
            if(item.getLore() != "" && item.getLore()[0].includes("|") && item.getLore()[0].includes("¡")) {
                let just = item.getLore()[0].split('|')
                let part = just[2].split('P')
                let no = [`${just[0]}|${just[1]}|P3P${part[2]}P${part[3]}P${part[4]}P${part[5]}P${part[6]}P${part[7]}P${part[8]}|`,item.getLore()[1]]
                item.setLore(no)
                player.getComponent('equippable')?.setEquipment(EquipmentSlot.Mainhand, item)
            }
        }
    })
}

export function hiltSelector(player) {
    let HiltSelector =
        new ActionFormData()
            .title('Selector')
            .body('')
            .button(`Blade`)
            .button(`Hilt`)
            .button(`Handle`)
            .button(`Guard`)
            .button(`Pommel`)
            .button(`Fling`)
            .button(`Sheath`)
            .button(`Sheath Style`)
            .button(`Cancel`)
            .button(`Confirm`)
            .button(`0`)
            .button(`1`)
            .button(`2`)
            .button(`3`)
            .button(`4`)
            .button(`5`)
            .button(`6`)
            .button(`7`)
            .button(`8`)
            .show(player)
            .then(result => {
            if (result.selection === 0) {
                bladeSelector(player)
            }
            if (result.selection === 1) {
                hiltSelector(player)
            }
            if (result.selection === 2) {
                handleSelector(player)
            }
            if (result.selection === 3) {
                guardSelector(player)
            }
            if (result.selection === 4) {
                pommelSelector(player)
            }
            if (result.selection === 5) {
                flingSelector(player)
            }
            if (result.selection === 6) {
                sheathSelector(player)
            }
            if (result.selection === 7) {
                sheathStyleSelector(player)
            }
            if (result.selection === 8) {
                Confirm(player)
            }
        })
}