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 customCommands extends registerSystem {
    constructor() {
        super();
        this.listenForEvent("minecraft:scriptEventReceive", (eventData) => {
            let { id, initiator, message, sourceBlock, sourceEntity, sourceType } = eventData;
            if (id === "get:stand" || id === "remove:stand") {
                let selector = message.split(" ")[0];
                let stand_name = message.split(" ")[1];
                
                let effect = (selectorx,position,target) => {
                    let pos = "xyz".split("").map(xyz => {
                        return position[xyz];
                    }).join(" ");
                    let get_effect = [
                        `execute positioned ${pos} run tag ${selectorx} add standMaster.${stand_name}`,
                        `execute positioned ${pos} run tag ${selectorx} add addStandData`,
                        `execute positioned ${pos} run effect @s regeneration 10 100 true`
                    ]
                    let remove_effect = [
                        `execute positioned ${pos} run tag ${selectorx} remove standMaster.${stand_name}`,
                        `execute positioned ${pos} run tag ${selectorx} add clearStandData`,
                        `execute positioned ${pos} run title ${selectorx} actionbar ui.empty`
                    ]
                    if (id === "get:stand" && !sourceEntity?.getTags().join("|").includes("standMaster.")) {
                        this.runCommands(get_effect, target)
                    }
                    if (id === "remove:stand") {
                        this.runCommands(remove_effect, target)
                    }
                }
                if (sourceEntity !== undefined) {
                    effect(selector, sourceEntity?.location, sourceEntity)
                }
            }
            if (id === "set:willPower") {
                let command = (position, target = message.split(" ")[1]??="@s", value = parseInt(message.split(" ")[0])) => {
                    let pos = "xyz".split("").map(xyz => {
                        return position[xyz];
                    }).join(" ");
                    return `execute positioned ${pos} run tag ${target} add mentalValue_${value}`
                }
                if (sourceEntity !== undefined && sourceEntity?.typeId === "minecraft:player") {
                    let player = sourceEntity;
                    this.runCommand(command(player?.location), player)
                }
                if (sourceBlock !== undefined) {
                    let block = sourceBlock;
                    this.runCommand(command(block?.location), this.getDimension("overworld"))
                }
            }
        });
    }
    
}
new customCommands()