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

export default class titleUI extends registerSystem {
    constructor(target) {
        super();
        this.player = target;
        this.debugToggle = this.GlobalVar(this.player,"debugToggle");
        this.isStandMaster = this.player?.getTags().join("|").includes("standMaster.");
        this.json_text = (ui) => {
            return JSON.stringify({rawtext:[{text:ui}]});
        }
    }
    loadingUI(ui) {
        this.runCommand(`titleraw @s title ${this.json_text(ui)}`, this.player);
    }
    loadingUI2(ui) {
        // this.runCommand(`title @s subtitle ${ui}`, this.player);
        this.player?.onScreenDisplay.setTitle(ui);
    }
    loadingUI3(ui,effect_ui = undefined) {
        // this.runCommand(`title @s title ${ui}`, this.player);
        if (effect_ui !== undefined) {
            this.player?.onScreenDisplay.setTitle(ui,{subtitle:effect_ui});
        } else {
            this.player?.onScreenDisplay.setTitle(ui);
        }
    }
    loadingGUI(data = {}) {
        // let i = 0;
        
        let { name, value } = data;
        name??="empty";
        
        let empty_line_wrap = range(1,4).map(v => {
            return "§r "
        }).join("\n\n\n");
        let color = {
            x: "§b",
            y: "§a",
            z: "§c"
        }
        let geo_method = (key) => {
            return key !== "getLocation" ? this.player[key]() : this.player["location"]
        }
        let xyz = (key) => {
            return [
                {
                    translate: `ui.debug.${key}`,
                    with: "xyz".split("").map(p => {
                        return geo_method(key)[p].toFixed(2);
                    })
                },
                "\n"
            ]
        }
        let xy = (key) => {
            return [
                {
                    translate: `ui.debug.${key}`,
                    with: "xy".split("").map(p => {
                        return geo_method(key)[p].toFixed(2);
                    })
                },
                "\n"
                // "§r" + this.player?.hasComponent("minecraft:scale")
            ]
        }
        let lc = "xyz".split("").map(xyz => {
            return this.getLc(this.player)[xyz].toFixed(2)
        }).join(" ")
        let debug_text_list = [
            `§r\n§e[debug]§r\n`,
            ...xyz("getVelocity"),
            ...xyz("getViewDirection"),
            ...xyz("getLocation"),
            ...xyz("getHeadLocation"),
            ...xy("getRotation"),
            "\n"
        ]
        let debug_text = this.debugToggle.var ? debug_text_list : range(1,debug_text_list.length / 2 + 2).map(v => {
            return "§r \n"
        })
        
        let mobId = this.GlobalVar(this.player,"mobId");
        let mobHealthVisible = this.GlobalVar(this.player,"mobHealthVisible");
        let getMobHealth = this.GlobalVar(this.player,"mobHealthValue");
        let getMobMaxHealth = this.GlobalVar(this.player,"mobMaxHealthValue");
        
        let ui_theme = this.GlobalVar(this.player,"statusBarUI_theme");
        
        let shealth = this.GlobalVar(this.player,"standMaster.health");
        let shealth_max = this.GlobalVar(this.player,"standMaster.health_max");
        
        let mental_value = this.GlobalVar(this.player,"mental_value");
        let mental_infinite = this.GlobalVar(mc.world,"mental.is_infinite");
        
        let line_wrap = (value) => {
            return range(0,value).map(v => {
                return "\n"
            }).join("")
        }
        
        let willPower_value = mental_infinite.var ? 70 : Mathf.clamp(mental_value.var,0,70);
        
        let willPowerUI = new standMaster_willPower();
        let healthUI = new standMaster_health();
        
        let red_number = (value) => {
            return value.toString().split("").map(v => {
                return "".split("")[parseInt(v)]
            }).join("");
        }
        let red_slash = ""
        
        let blue_number = (value) => {
            if (mental_infinite.var) {
                return "";
            } else {
                return value.toString().split("").map(v => {
                    return "".split("")[parseInt(v)]
                }).join("");
            }
        }
        let blue_slash = ""
        let number = (v) => {
            let zero = [
                null,
                "xx",
                "x",
                ""
            ]
            return zero[v.toString().split("").length] + v;
        }
        let number2 = (v) => {
            let zero = [
                null,
                "0",
                ""
            ]
            return zero[v.toString().split("").length] + v;
        }
        let number3 = (v) => {
            let zero = [
                null,
                "xxx",
                "xx",
                "x",
                ""
            ]
            return zero[v.toString().split("").length] + v;
        }
        
        // let stand_name = name;
        // let length = stand_name.split("").length;
        
        let stand_name = (name) => {
            let string_array = name.split("");
            let max_index = 32 - string_array.length;
            for (let i = 0; i < max_index; i++) {
                string_array.push("#")
            }
            let result = string_array.join("");
            return result
        }
        
        let sH_percent = number(100 - Math.round((shealth.var / (shealth_max.var + 5) * 10000) / 100))
        let sWP_percent = number(100 - Math.round((willPower_value / 71 * 10000) / 100))
        
        let sH_number = [
            number3(Math.floor(Mathf.clamp(shealth.var,0,shealth_max.var))),
            "/",
            number3(shealth_max.var),
        ].join("")
        let sWP_number = [
            number3(willPower_value),
            "/",
            number3(70),
        ].join("")
        // console.error(stand_name(name))
        
        let skill_slot_data = value.map(v => {
            let number_fill = (n,fill_count) => {
                let string_array = n.toString().split("");
                let max_index = fill_count - string_array.length;
                for (let i = 0; i < max_index; i++) {
                    string_array.unshift("x")
                }
                let result = string_array.join("");
                return result
            }
            let data_array = v.split("|")
            let selected_visible = JSON.parse(data_array[0]);
            let number = {
                current: parseFloat(data_array[1]),
                max: parseFloat(data_array[2]),
                count: parseInt(data_array[3])
            }
            let percent = number_fill(Math.round((number.current / number.max * 10000) / 100),3)
            // 21 sV129-128 P134-131 N141-136 C146-143
            let r = `sV${+selected_visible}_P${percent}_N${number_fill(number.current + (number.current === Math.floor(number.current) ? ".0" : ""),5)}_C${number_fill(number.count,3)}X`
            // console.error(r)
            return r
        })
        
        let ui_data = [
            this.isStandMaster ? `@stand_skillSlotsUI_skin${ui_theme.var}X` : `@standGHIJKLMNOPQRSTUVWXYZ`,// 26
            `standName${stand_name(name)}X`,// 42 67 - 35
            `mobHP${+mobHealthVisible.var}_${number(100 - Math.round((getMobHealth.var / getMobMaxHealth.var * 10000) / 100))}X`,// 11
            `debug${+this.debugToggle.var}X`,// 7
            `sH${sH_percent}X`,// 6
            `sWP${sWP_percent}X`,// 7
            `sHn${sH_number}X`,// 13
            `sWPn${sWP_number}X`,// 14
            ...skill_slot_data,
            `§r`
        ]
        // console.error(sH_percent)
        let list = [
            ui_data.join(""),
            "<line_wrap>32",
            {
                translate: mobId.var
            },
            ` §r§l${getMobHealth.var}/${getMobMaxHealth.var}§r`,
            "<line_wrap>32",
            ...debug_text,
            "<line_wrap>32",
            `§rempty`
        ]
        // let text = list.join("");
        let text = list.map(value => {
            if (typeof value === "string" && value.startsWith(`<line_wrap>`)) {
                return {
                    text: line_wrap(parseInt(value.replaceAll("<line_wrap>","")))
                }
            }
            if (value instanceof Object) {
                return value
            } else {
                return {
                    text: value
                }
            }
        })
        let json_text = {
            rawtext: text
        }
        this.player?.onScreenDisplay.setActionBar(json_text)
        // console.error(JSON.stringify(json_text))
        // this.player?.onScreenDisplay.setActionBar("hello world")
    }
}