import * as mc from "@minecraft/server";
import Vec3 from "../../../modules/Vec3.js";
import range from "../../../modules/arrayRange.js";
import Mathf from '../../../modules/Mathf.js';
import registerSystem from "../../../register/registerSystem.js";

export default class Initialize extends registerSystem {
    constructor() {
        super();
        this.listenForEvent("custom:playerJoin", (eventData) => this.playerJoin(eventData));
        this.listenForEvent("minecraft:worldInitialize", (eventData) => this.worldInitialize(eventData));
    }

    worldInitialize(eventData) {
        let def = new mc.DynamicPropertiesDefinition();
        let defx = new mc.DynamicPropertiesDefinition();
        let def2 = new mc.DynamicPropertiesDefinition();
        defx.defineNumber("exploding_timer");
        let list1 = [
            
            "statusBarUI_theme",
            
            "stand_skill1",
            "stand_skill2",
            "stand_skill3",
            "stand_skill4",
            "stand_skill1_2",
            "stand_skill2_2",
            "stand_skill3_2",
            "stand_skill4_2",
            
            "stand_pa",
            
            
            
            "standMaster.health",
            "standMaster.health_max",
            "mobHealthTick",
            "mobHealthValue",
            "mobMaxHealthValue",
            
            "mental_value",
            "mental_reply",
            "mental_timer",
            
            "playerHealth",
            "playerHealth2",
            
            "stand_fp_offset",
            
            "epitaph_distance",
            "delay_tick"
        ].forEach(value => {
            def.defineNumber(value);
        })
        
        let list2 = [
            "ui_type->32",
            "timeStopColor->32",
            "clicked_blockFace->32",
            "goldExperience.entity->32",
            "playerGameMode->32",
            "line_wrap->64",
            "epitaph_position->64",
            "epitaph_vector->64",
            "mobId->64",
            "stand_slotData0->24",
            "stand_slotData1->24",
            "stand_slotData2->24",
            "stand_slotData3->24"
        ].forEach(value => {
            let name = value.split("->")[0];
            let length = parseInt(value.split("->")[1]);
            def.defineString(name,length);
        })
        
        let list3 = [
            "barrage_camera_shake",
            "shoulder_surfing",
            "debugToggle",
            "mobHealthToggle",
            "mobHealthVisible"
        ].forEach(value => {
            def.defineBoolean(value);
        })
        
        let list4 = [
            "mental.is_infinite",
            "mental.can_recovery",
            "clear_tnts",
            "clear_items",
            "itemUseEvent"
        ].forEach(value => {
            def2.defineBoolean(value);
        })
        
        let list5 = [
            "stand_range_limit"
        ].forEach(value => {
            def2.defineNumber(value);
        })
        
        eventData.propertyRegistry.registerEntityTypeDynamicProperties(def, "minecraft:player");
        eventData.propertyRegistry.registerEntityTypeDynamicProperties(defx, "minecraft:tnt");
        eventData.propertyRegistry.registerEntityTypeDynamicProperties(defx, "minecraft:creeper");
        eventData.propertyRegistry.registerWorldDynamicProperties(def2);
    }
    
    playerJoin(eventData) {
        
        let player = eventData.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, Math.round(player?.getRotation()[xy]) ]
        }))
        // let item = player?.dimension.spawnItem(new mc.ItemStack("jojo:noriaki_porridge"),pos)?.getComponent("item").itemStack
        // this.scoresCreate(eventData);
        player?.addTag("not.mobHPUI");
        player?.addTag("stand.fist_isCooldown");
        player?.addTag("kc.epitaph_cooldown");
        player?.addTag("kc.erase_cooldown");
        player?.addTag("tw.timestop_cooldown");
        if (player?.hasTag("entity.in_timeErase")) {
            player?.addTag("remove.timeErase");
        }
        if (player?.hasTag("entity.in_timeStop")) {
            player?.addTag("remove.timeStop");
        }
        
        player?.removeTag("standMaster.death");
        
        let text = [ "start", ...range(1,7), "end" ].map(v => {
            return "<translate>ui.stand_settings.3.addon.golden_wind.description." + v
        })
        this.GlobalVar(mc.world,"itemUseEvent").var=false;
        
        this.GlobalVar(player,"stand_slotData0").var="0|100|1|NaN";
        this.GlobalVar(player,"stand_slotData1").var="0|100|1|NaN";
        this.GlobalVar(player,"stand_slotData2").var="0|100|1|NaN";
        this.GlobalVar(player,"stand_slotData3").var="0|100|1|NaN";
        this.GlobalVar(player,"debugToggle").var??=false;
        this.GlobalVar(player,"delay_tick").var??=-1;
        this.GlobalVar(player,"playerHealth").var??=20;
        this.GlobalVar(player,"playerHealth2").var??=20;
        this.GlobalVar(player,"mobHealthToggle").var??=false;
        this.GlobalVar(player,"mobHealthVisible").var=false;
        this.GlobalVar(player,"mobHealthTick").var=0;
        this.GlobalVar(player,"mobHealthValue").var=0;
        this.GlobalVar(player,"mobMaxHealthValue").var=0;
        this.GlobalVar(player,"statusBarUI_theme").var??=1;
        this.GlobalVar(player,"standMaster.health").var??=200;
        this.GlobalVar(player,"standMaster.health_max").var??=200;
        this.GlobalVar(player,"mental_value").var??=70;
        this.GlobalVar(player,"mental_reply").var??=0;
        this.GlobalVar(player,"mental_timer").var=0;
        this.GlobalVar(player,"barrage_camera_shake").var??=true;
        this.GlobalVar(player,"shoulder_surfing").var??=false;
        this.GlobalVar(player,"stand_fp_offset").var??=35;
        this.GlobalVar(mc.world,"stand_range_limit").var??=0;
        this.GlobalVar(mc.world,"clear_tnts").var??=true;
        this.GlobalVar(mc.world,"clear_items").var??=true;
        this.GlobalVar(mc.world,"mental.is_infinite").var??=false;
        this.GlobalVar(mc.world,"mental.can_recovery").var??=true;
        this.GlobalVar(player,"timeStopColor").var??="white";
        this.GlobalVar(player,"goldExperience.entity").var??="goldexperience:tree";
        this.GlobalVar(player,"mobId").var="empty";
        this.GlobalVar(player,"ui_type").var="@ui.stand.mental->";
        
        let message = this.listMessage(...text);
        this.runCommand(`tellraw @s ${message}`, player);
        let list2 = [
            "stand_skill1",
            "stand_skill1_2",
            "stand_skill2",
            "stand_skill2_2",
            "stand_skill3",
            "stand_skill3_2",
            "stand_skill4",
            "stand_skill4_2",
            
            "stand_pa"
        ];
        list2.forEach(value => {
            this.GlobalVar(player,value).var=0;
        })
        this.GlobalVar(player,"mental_value").var??=70;
        
        let array = [];
        for (let i of range(0,63)) {
            array.push("\n")
        }
        this.GlobalVar(player,"line_wrap").var = array.join("")
        
        // this.runCommand(`playanimation @s animation.stand.first_person_offset.variable.${stand_fp_offset.var} default 1`, player);
    }

    listMessage(...texts) {
        let i = 0;
        let array = [...texts];
        
        while (i <= array.length) {
            array.splice(i, 0, "\n");
            i += 2;
        }
        let object = array.slice(1).slice(0, -1).map(v => {
            if (v === "\n") {
                return {
                    text: v
                }
            } else if (v.startsWith("<text>")) {
                return {
                    text: v.replaceAll("<text>","")
                }
            } else if (v.startsWith("<translate>")) {
                return {
                    translate: v.replaceAll("<translate>","")
                }
            }
        });
        
        let textJson = JSON.stringify({
            rawtext: [
                ...object
            ]
        })
        return textJson;
    }
}

new Initialize()