import * as mc from "@minecraft/server";
import * as mcui from "@minecraft/server-ui";
import titleUI from "./default//standUI.js";
import Vec3 from "../../modules/Vec3.js";
import Mathf from "../../modules/Mathf.js";
import range from "../../modules/arrayRange.js";
import registerSystem from "../../register/registerSystem.js";

import "./default/settings_menu.js";
import "./default/initialize.js";
import "./default/customCommands.js";

import standMaster_health from "./default/standMaster_health.js";
import standMaster_willPower from "./default/standMaster_willPower";

import standIndex from "./list/_standIndex_.js";

// import "./list/kingCrimson/_main_.js";
// import "./list/goldExperience/_main_.js";


class StandScript extends registerSystem {
    constructor() {
        super();
        this.stand_list = Object.keys(standIndex);
        this.stand = /stand:skill1/;
        
        this.listenForEvent("minecraft:beforeWatchdogTerminate", (eventData) => {
            eventData.cancel = true;
        })
        
        this.healthSystem = new standMaster_health().events();
        this.willPowerSystem = new standMaster_willPower().events();
        
        this.stand_list.forEach(stand => {
            return standIndex[stand].eventData(this);
        })
        this.tick(() => this.stand_ticking(),1);
        this.tick(() => {
            let players = this.getPlayers();
            if (players.length > 0) {
                players.forEach(player => {
                    let handItem = this.getHandItem(player);
                    let pos = Object.fromEntries("xyz".split("").map(xyz => {
                        return [ xyz, Math.round(player?.location[xyz]) ]
                    }))
                    let rot = Object.fromEntries("xy".split("").map(xy => {
                        return [ xy, player?.getRotation()[xy].toFixed(2) ]
                    }))/*
                    if (handItem?.typeId === "jojo:noriaki_porridge" ) {
                    }*/
                    if (handItem?.typeId === "minecraft:diamond_sword" && player?.isSprinting) {
                        // let lc = this.getLc(player);
                        // let power = 1;
                        // player?.applyKnockback(lc.x, lc.z, power * this.getLc2(-90,0).y - Math.abs(Math.round(player?.getViewDirection().y)), player?.getViewDirection().y * power);
                        // player?.applyKnockback(0,0,0,player?.getVelocity().y * 0.65);
                    }
                })
            }
        })
        
        this.stand_ticking = () => {
            this.stand_list.forEach(stand => {
                let players = this.getPlayers({tags:[`standMaster.${stand}`]/*,excludeTags:["ui_using"]*/});
                if (players.length > 0) {
                    players.forEach(player => {
                        return new standIndex[stand](player);
                    })
                }
            })
        };
        
        
        
        /*
        this.listenForEvent("minecraft:itemUseOn", (eventData) => {
            let { source, item } = eventData;
            if (item.typeId === "minecraft:diamond_sword") {
                let lc = this.getLc(source);
                source.applyKnockback(lc.x,lc.z,2,source.getViewDirection().y)
            }
        });
        */
        /*
        this.tick(() => {
            this.getPlayers().forEach(player => {
                let item = this.getHandItem(player);
                if (item.typeId === "minecraft:diamond_sword") {
                    let block = player?.getBlockFromViewDirection();
                    if (block !== undefined && block !== null) {
                        let sign = block.getComponent("minecraft:sign");
                        console.error(sign.getText());
                    }
                }
            })
        },15);
        this.listenForEvent("minecraft:entityHit", (eventData) => {
            let { entity, hitEntity } = eventData;
            let item = this.getHandItem(entity);
            if (item?.typeId === "minecraft:diamond_sword") {
                hitEntity?.setOnFire(10)
            }
        })*/
        /*
        this.tick(() => {
            this.getPlayers().forEach(player => {
                let item = this.getHandItem(player);
                if (item?.typeId === "weapon:flying_knife") {
                    let enchantments = item?.getComponent("minecraft:enchantments").enchantments;
                    enchantments.addEnchantment(new mc.Enchantment({id:"knockback"},100));
                }
            })
        },1),*/
        this.listenForEvent("minecraft:chatSend", (eventData) => this.chat(eventData));
        this.listenForEvent("minecraft:itemStartUse", (eventData) => this.stand_startsAttack(eventData));
        this.listenForEvent("minecraft:itemStopUse", (eventData) => this.stand_stopsAttack(eventData));
        this.listenForEvent("minecraft:itemStartUse", (eventData) => this.stand_disc(eventData));
        this.listenForEvent("minecraft:entityDie", (eventData) => this.entityDeath(eventData));
        this.listenForEvent("minecraft:itemStopUse", (eventData) => this.foodSystem(eventData));
        /*
        this.listenForEvent("minecraft:entityHealthChanged", (eventData) => {
            let { entity, newValue, oldValue } = eventData;
            if (entity?.typeId === "minecraft:player") {
                console.error(`\nnewValue:${newValue}\noldValue:${oldValue}`)
            }
        })
        */
        this.listenForEvent("minecraft:entitySpawn", (eventData) => {
            let { entity } = eventData;
            if (entity?.typeId !== "minecraft:player") {
                entity?.addTag("isFirstCreated")
            }
            if (entity?.typeId === "minecraft:tnt") {
                let timer = this.GlobalVar(entity,"exploding_timer");
                timer.var??=0;
                this.runCommand(`event entity @s delay_explosion`, entity)
            }
        })
        this.tick(() => {
            this.getEntities({type:"tnt"}).forEach(entity => {
                let fuse_length = [
                    4,
                    Mathf.random(0.5,2.0)
                ];
                let pos = Object.fromEntries("xyz".split("").map(xyz => {
                    return [ xyz, entity?.location[xyz] ]
                }))
                let timer = this.GlobalVar(entity,"exploding_timer");
                timer.var??=0;
                if (entity?.hasTag("entity.in_timeStop")) {
                    this.runCommand(`event entity @s no_explosion`, entity)
                    entity?.removeTag("start_explosion")
                    entity?.removeTag("delay_explosion")
                } else {
                    timer.var += 1;
                    if (timer.var >= fuse_length[+entity?.hasTag("from_explosion")] * 20) {
                        if (!entity?.hasTag("start_explosion")) {
                            this.runCommand(`event entity @s start_explosion`, entity)
                            entity?.addTag("start_explosion")
                        }
                    } else {
                        if (!entity?.hasTag("delay_explosion")) {
                            this.runCommand(`event entity @s delay_explosion`, entity)
                            entity?.addTag("delay_explosion")
                        }
                    }
                }
            })
            this.getEntities({type:"creeper"}).forEach(entity => {
                let fuse_length = 1.5;
                let pos = Object.fromEntries("xyz".split("").map(xyz => {
                    return [ xyz, entity?.location[xyz] ]
                }))
                let timer = this.GlobalVar(entity,"exploding_timer");
                timer.var??=0;
                if (entity?.hasTag("entity.in_timeStop")) {
                    if (entity?.hasTag("start.exploding") || entity?.hasTag("start.exploding.forced")) {
                        this.runCommand(`event entity @s custom:exploding_in_timeStop`, entity)
                        entity?.removeTag("start_explosion")
                        entity?.removeTag("delay_explosion")
                        entity?.addTag("delayed_reaction")
                    }
                } else {
                    if (entity?.hasTag("start.exploding") || entity?.hasTag("start.exploding.forced")) {
                        timer.var += 1;
                        if (timer.var >= fuse_length * 20) {
                            if (!entity?.hasTag("start_explosion")) {
                                this.runCommand(`event entity @s custom:start_exploding`, entity)
                                entity?.addTag("start_explosion")
                            }
                        } else {
                            if (!entity?.hasTag("delay_explosion")) {
                                if (entity?.hasTag("start.exploding") && !entity?.hasTag("delayed_reaction")) {
                                    this.runCommand(`event entity @s minecraft:start_exploding`, entity)
                                }
                                if (entity?.hasTag("start.exploding.forced") || entity?.hasTag("delayed_reaction")) {
                                    this.runCommand(`event entity @s minecraft:start_exploding_forced`, entity)
                                    entity?.removeTag("delayed_reaction")
                                }
                                entity?.addTag("delay_explosion")
                            }
                        }
                    } else {
                        timer.var = 0;
                    }
                }
            })
        })
        this.tick(() => {
            this.getEntities({tags:["isFirstCreated"]}).forEach(entity => {
                entity?.removeTag("entity.in_timeErase")
                entity?.removeTag("isFirstCreated")
            })
        },30)
        this.listenForEvent("minecraft:entityHitEntity", (eventData) => {
            let { damagingEntity, hitEntity } = eventData;
            let entity = damagingEntity;
            let isStandMaster = entity?.getTags().join("|").includes("standMaster.");
            if (entity?.typeId === "minecraft:player" && isStandMaster && this.getHandItem(entity)?.typeId === "stand:skill1") {
                entity?.addTag("stand.pa");
                if (hitEntity?.hasComponent("minecraft:movement")) {
                    hitEntity?.addTag("stand.damageBy:" + entity?.nameTag);
                } else if (hitEntity?.typeId !== "minecraft:ender_dragon") {
                    this.runCommand(`damage @s 0 entity_attack entity @a[name="${entity?.nameTag}"]`, hitEntity);
                }
            }
        })
        this.listenForEvent("minecraft:entityHitEntity", (eventData) => {
            let { damagingEntity, hitEntity } = eventData;
            let entity = damagingEntity;
            let isStandMaster = entity?.getTags().join("|").includes("standMaster.");
            if (entity?.typeId === "minecraft:player") {
                let velocity = Object.fromEntries("xyz".split("").map(xyz => {
                    return [ xyz, this.getLc(entity)[xyz] * 1.23 ]
                }))
                if (!hitEntity?.hasComponent("minecraft:movement")) {
                    if (hitEntity?.hasTag("entity.in_timeStop")) {
                        let overlayVelocity = Object.fromEntries("xyz".split("").map(xyz => {
                            return [ xyz, {var:0} ]
                        }))
                        "xyz".split("").map(xyz => {
                            try {
                                overlayVelocity[xyz] = this.scores(hitEntity,"overlayVelocity" + xyz.toUpperCase());
                            } catch(e) {
                                overlayVelocity[xyz] = {
                                    var: 0
                                }
                            }
                            overlayVelocity[xyz].var = velocity[xyz].toFixed(2) * 100
                        })
                    }
                    if (hitEntity?.hasTag("entity.in_timeErase")) {
                        let eraseVelocity = Object.fromEntries("xyz".split("").map(xyz => {
                            return [ xyz, {var:0} ]
                        }))
                        "xyz".split("").map(xyz => {
                            try {
                                eraseVelocity[xyz] = this.scores(hitEntity,"eraseVelocity" + xyz.toUpperCase());
                            } catch(e) {
                                eraseVelocity[xyz] = {
                                    var: 0
                                }
                            }
                            eraseVelocity[xyz].var = velocity[xyz].toFixed(2) * 100
                        })
                    }
                }
            }
        })
        /*
        this.listenForEvent("minecraft:itemUse", (eventData) => {
            let { source, item } = eventData;
            if (item?.typeId === "weapon:flying_knife") {
                let rot = source.getRotation();
                this.runCommand(`playsound knife.flying @a ~ ~ ~`, source);
                let projectile = this.shoot(source, item?.typeId, 3/10, [0,1.3,0]);
                projectile.addTag("owner:" + source.nameTag)
                projectile.setRotation(-rot.x,-rot.y)
            }
        });*/
        this.listenForEvent("minecraft:projectileHitBlock", (eventData) => {
        let { source, projectile } = eventData;
            projectile?.addTag("theWorld.timeStop");
            projectile?.addTag("projectile.isHit");
            if ((projectile?.typeId === "purplehaze:virus_maru" || projectile?.typeId === "weapon:flying_knife") && source?.typeId === "minecraft:player") {
                let player = source;
                projectile?.addTag("owner:" + player?.nameTag)
            }
        });
        this.listenForEvent("minecraft:projectileHitEntity", (eventData) => {
            let { source, projectile } = eventData;
            if (projectile?.typeId === "weapon:flying_knife" && source?.typeId === "minecraft:player") {
                let player = source;
                let hitEntity = eventData.getEntityHit()?.entity;
                let health = hitEntity?.getComponent("minecraft:health");
                let damageType = [
                    "entity_attack",
                    "suicide"
                ]
                let damage = hitEntity?.typeId === "minecraft:player" ? 2 : 5;
                projectile?.addTag("owner:" + player?.nameTag)
                // this.runCommand(`damage @s ${damage} ${damageType[+(health?.currentValue > damage)]} entity @a[name="${player?.nameTag}"]`, hitEntity)
                this.runCommand(`damage @s[type=!tnt] ${damage} ${damageType[1]} entity @a[name="${player?.nameTag}"]`, hitEntity)
            }
            if (projectile?.typeId === "purplehaze:virus_maru") {
                projectile?.addTag("owner:" + source?.nameTag)
                projectile?.teleport({
                    x: projectile.location.x,
                    y: projectile.location.y,
                    z: projectile.location.z
                })
            }
        });
        // this.listenForEvent("minecraft:entitySpawn", (eventData) => this.scoresCreate(eventData));
        this.tick(() => this.update(),1);
        /*
        this.tick(() => {
            // Green Day!
            this.getPlayers().forEach(player => {
                if (player?.getVelocity().y < 0) {
                    player?.applyDamage(Math.abs(Math.round(player?.getVelocity().y * 10) + 1))
                }
            })
        },1);*/
        this.tick(() => {
            let players = this.getPlayers();
            if (players.length > 0) {
                players.forEach(player => {
                    let handItem = this.getHandItem(player);
                    let knife_count = this.scores(player, "knife_count");
                    if (handItem?.typeId === "weapon:flying_knife_item") {
                        knife_count.var = handItem?.amount;
                    }
                    this.runCommand(`tag @e[r=2.13,type=weapon:flying_knife] add can.picked_up`, player)
                    let knifes = this.getEntities({type:"weapon:flying_knife",tags:["can.picked_up"]}).filter(e => e?.hasTag("owner:" + player?.nameTag))
                    if (knifes.length > 0) {
                        knifes.forEach(knife => {
                            let inventory = player?.getComponent("inventory")?.container;
                            let itemStack = new mc.ItemStack(mc.ItemTypes.get("weapon:flying_knife_item"));
                            inventory?.addItem(itemStack);
                            this.runCommand(`event entity @s despawn`, knife)
                        })
                    }
                })
            }
        },1)
        this.tick(() => {
            let items = this.getEntities({type: "item"}).filter(item => item.getComponent("minecraft:item").itemStack.typeId.split(":")[0] == "stand");
            if (items.length > 0) {
                items.forEach(item => {
                    item.kill();
                })
            }
            // this.scoresCreate();
            
            this.getPlayers().forEach(player => {
                this.runCommand(`tag @s[hasitem={item=jojo:stand_settings,quantity=0}] add stand.no_settings`, player)
                
                let check = player?.getTags().join("|");
                let inventory = player?.getComponent("inventory").container;
                if (!check?.includes("standMaster.")) {
                    for (let slot of range(0,inventory.size - 1)) {
                        let item = inventory.getItem(slot);
                        if (item !== undefined) {
                            if (item.typeId.split(":")[0] == "stand") {
                                this.runCommand(`clear @s ${item.typeId} 0 999`, player);
                            }
                        }
                    }
                }
                
            })
        },10)
        this.tick(() => {/*
            this.getEntities({type:["wither"]}).forEach(entity => {
                let health = entity?.getComponent("minecraft:health");
                entity?.nameTag = entity?.typeId + " " + Math.round(health?.currentValue) + "/" + Math.round(health?.defaultValue)
            })*/
            this.getPlayers().forEach(player => {
                let debugToggle = this.GlobalVar(player,"debugToggle");
                let mobId = this.GlobalVar(player,"mobId");
                let mobHealthTick = this.GlobalVar(player,"mobHealthTick");
                let mobHealthToggle = this.GlobalVar(player,"mobHealthToggle");
                let mobHealthVisible = this.GlobalVar(player,"mobHealthVisible");
                let mobHealthValue = this.GlobalVar(player,"mobHealthValue");
                let mobMaxHealthValue = this.GlobalVar(player,"mobMaxHealthValue");
                
                let isStandMaster = player?.getTags().join("|").includes("standMaster");
                let alwaysVisible = isStandMaster || debugToggle.var;
                
                let ui = new titleUI(player);
                
                if (player?.hasTag("addStandData")) {
                    player?.addTag("stand.fist_isCooldown");
                    player?.addTag("kc.epitaph_cooldown");
                    player?.addTag("kc.erase_cooldown");
                    player?.addTag("tw.timestop_cooldown");
                    player?.removeTag("addStandData");
                }
                if (player?.hasTag("clearStandData")) {
                    for (let i of range(1,4)) {
                        this.GlobalVar(player,"stand_skill" + i).var = 0;
                        this.GlobalVar(player,"stand_skill" + i + "_2").var = 0;
                    }
                    player?.removeTag("clearStandData");
                }
                if (debugToggle.var && !isStandMaster) {
                    ui.loadingGUI();
                    player?.removeTag("not.debugUI");
                } else {
                    if (!player?.hasTag("not.debugUI")) {
                        player?.onScreenDisplay.setActionBar("ui.empty");
                        player?.addTag("not.debugUI");
                    }
                }
                if (mobHealthToggle.var) {
                    let entityFV = this.getEntitiesFromViewVector(player, 13).filter(e => e?.entity?.hasComponent("minecraft:health"))[0];
                    if (!player?.hasTag("not.mobHPUI") && !alwaysVisible) {
                        ui.loadingGUI();
                    }
                    if (entityFV === undefined) {
                        if (!player?.hasTag("not.mobHPUI")) {
                            mobHealthTick.var += 1;
                            if (mobHealthTick.var == 10) {
                                mobHealthVisible.var = false;
                                mobHealthValue.var = 0;
                                mobMaxHealthValue.var = 0;
                                if (!alwaysVisible) {
                                    player?.onScreenDisplay.setActionBar("ui.empty");
                                }
                                player?.addTag("not.mobHPUI");
                            }
                        } else {
                            mobHealthTick.var = 0;
                        }
                    }
                    if (entityFV !== undefined) {
                        let entity = entityFV?.entity;
                        let entity_isStandMaster = entity?.typeId === "minecraft:player" && entity?.getTags().join("|").includes("standMaster");
                        let shealth = entity_isStandMaster ? this.GlobalVar(player,"standMaster.health") : {var:0};
                        let shealth_max = entity_isStandMaster ? this.GlobalVar(player,"standMaster.health_max") : {var:0};
                        player?.removeTag("not.mobHPUI");
                        let health = entity?.getComponent("minecraft:health");
                        mobId.var = entity?.typeId === "minecraft:player" ? entity?.nameTag : `entity.${entity?.typeId.startsWith("minecraft:") ? entity?.typeId.replaceAll("minecraft:","") : entity?.typeId}.name`;
                        mobHealthTick.var = 0;
                        mobHealthVisible.var = true;
                        mobHealthValue.var = Math.max(0,Math.round(health?.currentValue + shealth.var));
                        mobMaxHealthValue.var = Math.max(0,Math.round(health?.defaultValue + shealth_max.var));
                    }
                } else {
                    mobHealthVisible.var = false;
                    mobHealthValue.var = 0;
                    mobMaxHealthValue.var = 0;
                    player?.addTag("not.mobHPUI");
                }
                
            })
        },1)
    }
    
    
    update() {
        let players = this.getPlayers();
        if (players.length > 0) {
            players.forEach(player => {
                let health = player?.getComponent("minecraft:health");
                
                player?.removeTag("standMaster.empty");
                let shealth = this.GlobalVar(player,"standMaster.health")
                let shealth_max = this.GlobalVar(player,"standMaster.health_max")
                let mental_value = this.GlobalVar(player,"mental_value")
                let mental_timer = this.GlobalVar(player,"mental_timer");
                
                
                if (player?.hasTag("stand.no_settings")) {
                    // console.error("hello world")
                    let inventory = player?.getComponent("inventory").container;
                    let itemStack = new mc.ItemStack(mc.ItemTypes.get("jojo:stand_settings"));
                    itemStack.keepOnDeath = true,
                    itemStack.lockMode = "slot",
                    // itemStack.nameTag = "hello world",
                    inventory?.setItem(8,itemStack)
                    player?.removeTag("stand.no_settings");
                }
                let tags = player?.getTags().filter(tag => tag.split("_")[0] == "mentalValue");
                if (tags?.length > 0) {
                    tags?.forEach(tag => {
                        mental_value.var = parseInt(tag.split("_")[1]);
                        
                        player?.removeTag(tag)
                    })
                }
                if (mental_value.var <= 0 && !player?.hasTag("player.no_mental")) {
                    player?.addTag("player.no_mental");
                } else {
                    player?.removeTag("player.no_mental");
                }
                if (player?.hasTag("isHurt")) {
                    /*
                    if (player?.hasTag("kingCrimson.timeErase") || player?.hasTag("kingCrimson.epitaph")) {
                        console.error("莎比眉目的麻将把瞬间治疗误判成实体受伤")
                    }
                    if (!player?.hasTag("kingCrimson.timeErase") && !player?.hasTag("kingCrimson.epitaph")) {
                        console.error("cnmd麻将瞬间治疗关了也要误判")
                    }
                    */
                    player?.removeTag("isHurt")
                }
                if (player?.hasTag("player.no_mental")) {
                    for (let effect of [ "hunger->20", "mining_fatigue->10", "slowness->3", "weakness->10" ]) {
                        let name = effect.split("->")[0];
                        let amplifier = parseInt(effect.split("->")[1]);
                        player?.addEffect(name, 20, {
                            amplifier: amplifier,
                            showParticles: false
                        });
                    }
                }
                if (player?.hasTag("standMaster.death") && health.currentValue > 0) {
                    mental_value.var = 70;
                    shealth.var = shealth_max.var;
                    player?.removeTag("standMaster.death");
                }
                
                
                
                
            })
        }
        
    }
    
    settings(eventData) {
        let { source, itemStack } = eventData;
        if (source.typeId === "minecraft:player") {
            let player = source;
            let item = itemStack;
            if (!player?.isSneaking && item.typeId == "jojo:stand_settings") {
                player?.addTag("ui.stand_settings.menu");
            }
        }
    }
    
    stand_disc(eventData) {
        let item = eventData.itemStack;
        let player = eventData.source;
        let check = player?.getTags();
        let includes = check.join("|").includes("standMaster.");
        if (item.typeId != "disc:empty" && player?.getItemCooldown("ender_pearl") === 0 && /disc:\w+/.exec(item.typeId) && !includes) {
            player?.startItemCooldown("ender_pearl",20)
            let stand_name = item.typeId.replace(/disc:/g,"").toLowerCase().replace(/_(\w)/g, (L) => L.toUpperCase()).replace(/_/g, "");
            this.runCommand(`scriptevent get:stand @s ${stand_name}`, player);
            this.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 disc:empty`, player);
        }
        if (item.typeId == "disc:empty" && player?.getItemCooldown("ender_pearl") === 0 && includes) {
            player?.startItemCooldown("ender_pearl",20)
            check.filter(tags => tags.includes("standMaster.")).forEach(stand_name => {
                let disc_name = "disc:" + stand_name.replace(/standMaster./g,"").split("").map(value => {
                    if (value == value.toUpperCase()) {
                        return "_" + value.toLowerCase();
                    } else {
                        return value;
                    }
                }).join().replace(/,/g,"");
                player?.removeTag(stand_name)
                this.runCommand(`scriptevent remove:stand @s ${stand_name}`, player);
                this.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 ${disc_name}`, player);
            })
        }
    }

    stand_startsAttack(eventData) {
        let c = (target) => {
            return target.typeId === "minecraft:player" && target.getTags().join("|").includes("standMaster.");
        }
        let { itemStack, source } = eventData;
        
        if (c(source)) {
            let item = itemStack;
            let player = source;
            if (item?.typeId === "stand:skill1") {
                if (player?.isSneaking) {
                    if (player?.hasTag("standMaster.kingCrimson")) {
                        this.runCommand(`tag @s add stand.APattack`, player)
                    }
                }
                if (!player?.isSneaking) {
                    this.runCommand(`tag @s[tag=kc.doubt] add stand.APattack`, player)
                    this.runCommand(`tag @s[tag=!kc.doubt] add stand.quick_fist`, player)
                }
            }
        }
    }
    stand_stopsAttack(eventData) {
        let c = (target) => {
            return target.typeId === "minecraft:player" && target.getTags().join("|").includes("standMaster.");
        }
        let { itemStack, source } = eventData;
        
        if (c(source)) {
            let item = itemStack;
            let player = source;
            if (item?.typeId === "stand:skill1") {
                this.runCommand(`tag @s remove stand.quick_fist`, player)
            }
        }
    }
    
    entityDeath(eventData) {
        let entity = eventData.deadEntity;
        try {
            for (let tag of ["isAttackedByFist","isHitByFist"]) {
                if (entity?.hasTag(tag)) {
                    entity?.removeTag(tag);
                }
            }
            if (entity?.typeId == "minecraft:player"/* && entity?.getTags().join("|").includes("standMaster.")*/) {
                
                // entity.addTag("standMaster.death");
                // entity.removeTag("stand.quick_fist");
                // entity.removeTag("stand.APattack");
                
                this.runCommands([
                    `tag @s add standMaster.death`,
                    `tag @s remove stand.quick_fist`,
                    `tag @s remove stand.APattack`,
                    `tag @s remove infected.purpleVirus`,
                    `tag @e[tag=entity.in_timeStop] add remove.timeStop`,
                    `tag @e[tag=entity.in_timeErase] add remove.timeErase`
                    // `tag @s remove theWorld.timeStop`,
                    // `tag @s remove kingCrimson.timeErase`
                ], entity)
            }
        } catch(e) {}
    }
    
    chat(eventData) {
        let player = eventData.sender;
        let message = eventData.message;
        if (message.startsWith("#D4C")) {
            let dimension = this.getDimension(message.split(":")[1]);
            player?.teleport({
                x: 0,
                y: 0,
                z: 0
            },{
                dimension: dimension
            });
        }
    }
    
    scoresCreate(eventData) {
    }
    
    
    foodSystem(eventData) {
        let item = eventData.itemStack;
        let entity = eventData.source;
        let mc_food = [
    		"apple->4",
    		"enchanted_golden_apple->4",
    		"baked_potato->5",
    		"beef->3",
    		"beetroot->1",
    		"beetroot_soup->6",
    		"bread->5",
    		"carrot->3",
    		"chicken->2",
    		"chorus_fruit->4",
    		"clownfish->1",
    		"cooked_beef->8",
    		"cooked_chicken->6",
    		"cooked_fish->5",
    		"cooked_porkchop->8",
    		"cooked_rabbit->5",
    		"cooked_salmon->6",
    		"cookie->2",
    		"dried_kelp->1",
    		"fish->2",
    		"golden_apple->4",
    		"golden_carrot->6",
    		"melon_slice->2",
    		"mushroom_stew->6",
    		"cooked_mutton->6",
    		"mutton->2",
    		"poisonous_potato->2",
    		"porkchop->3",
    		"potato->1",
    		"pufferfish->1",
    		"pumpkin_pie->8",
    		"rabbit->3",
    		"rabbit_stew->10",
    		"rotten_flesh->4",
    		"salmon->2",
    		"spider_eye->2",
    		"suspicious_stew->6",
    		"sweet_berries->2"
    	].map(v => {
    	    return "minecraft:" + v;
    	});
    	let addon_food = [
    	    "jojo:noriaki_porridge->100"
    	]
    	let food_list = [
    	    ...mc_food,
    	    ...addon_food
    	]
    	if (entity?.typeId === "minecraft:player") {
    	    let player = entity;
    	    let shealth = this.GlobalVar(player,"standMaster.health");
    	    let mental_value = this.GlobalVar(player,"mental_value");
    	    let mental_timer = this.GlobalVar(player,"mental_timer");
        	food_list.forEach(value => {
        	    let food = {
            	    id: value.split("->")[0],
            	    nutrition: parseInt(value.split("->")[1])
        	    }
        	    if (item?.typeId === food.id) {
                    let { useDuration } = eventData;
                    let { nutrition } = food;
        	        if (useDuration <= 0) {
        	            mental_value.var += nutrition;
        	            shealth.var += nutrition;
        	            mental_timer.var = 0;
        	        }
        	        // this.runCommand(`say d:${useDuration} n:${nutrition}`, player);
        	    }
        	})
        	/*
        	console.error(item?.hasComponent("minecraft:food"))
        	if (item?.hasComponent("minecraft:food") && item?.typeId.split(":")[0] !== "minecraft") {
    	        let cFood = item?.getComponent("minecraft:food");
    	        let { useDuration } = eventData;
    	        let { nutrition } = cFood;
    	        foodData(useDuration,nutrition);
    	        console.error(`${useDuration}\n${nutrition}`);
    	    }*/
	    }
    }

}

new StandScript();
