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

export default class standMaster_willPower extends registerSystem {
    constructor() {
        super();
        this.icons = {
            vanilla: "".split(""),
            rpg: "".split("")
        }
    }
    
    events() {
        this.tick(() => {
            this.getPlayers().forEach(player => {
                let mental_value = this.GlobalVar(player,"mental_value");
                let mental_recovery = this.GlobalVar(mc.world,"mental.can_recovery");
                mental_value.var += mental_recovery.var ? 1 : 0;
            })
        },200);
        this.tick(() => {
            this.getPlayers().forEach(player => {
                let mental_value = this.GlobalVar(player,"mental_value")
                mental_value.var = Mathf.clamp(mental_value.var,0,70);
                
                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)
                    })
                }
            })
        },1);
    }
    
    loadingUI(player, willPower, max_willPower, type) {
        let progress_bar = (player, willPower, max_willPower, min = 0, max = 9) => {
            let icons = this.icons[type];
            let count = range(1, max_willPower / 7).map(() => {
                return icons;
            })
            let result = count.map((icon,index) => {
                let icon_frame = icons.length - 1;
                let icon_count = index + 1;
                let value = icon[Mathf.clamp(icon_count * icon_frame - willPower, 0, icon_frame)] 
                return index >= min && index <= max ? value : "";
            });
            return type == "rpg" ? result.join("") : result.reverse().join("\n");
        }
        
        return progress_bar(player, willPower, max_willPower);
        
    }
    
}