import ActionForm from "./ActionForm.js";

export default class uiSystem {
    constructor() {
        this.uiArray;
        this.buttonList;
        this.triggerDef;
    }
    
    layout(player, value) {
        let uiArray = this.uiArray = value.replace(/    /g, "").split("\n").slice(1).slice(0, -1);
        let buttonList = this.buttonList = uiArray.slice(1).slice(0, -1).slice(1).slice(0, -1).slice(1).slice(0, -1);
        let uiS = uiArray[0];
        let uiE = uiArray[uiArray.length - 1];
        let titleS = uiArray[1];
        let titleE = uiArray[uiArray.length - 2];
        let bodyS = uiArray[2];
        let bodyE = uiArray[uiArray.length - 3];
        if ((uiS.startsWith(`<ui id="`) && uiS.endsWith(`"/>`)) && uiE.includes("</ui>")) {
            if ((titleS.startsWith(`<title text="`) && titleS.endsWith(`"/>`)) && titleE.includes("</title>")) {
                if ((bodyS.startsWith(`<body text="`) && bodyS.endsWith(`"/>`)) && bodyE.includes("</body>")) {
                    let customUI = new ActionForm();
                    customUI.title(titleS.split(`"`)[1]);
                    customUI.body(bodyS.split(`"`)[1]);
                    buttonList.forEach(value => {
                        let button = value.split(`"`);
                        if (button[0] == `<button id=` && button[2] == ` text=` && button[4] == `/>`) {
                            customUI.button(button[3]);
                        }
                        if (button[0] == `<button id=` && button[2] == ` text=` && button[4] == ` icon=` && button[6] == `/>`) {
                            customUI.button(button[3],button[5]);
                        }
                    })
                    customUI.show(player, (selection,canceled) => this.triggerDef(selection,canceled));
                }
            }
        }
    }
    
    
    trigger(id, def) {
        let uiArray = this.uiArray;
        let buttonList = this.buttonList;
        if (uiArray[0].split(`"`)[1] === id) {
            this.triggerDef = function(selection,canceled) {
                let e = {
                    getElementById: buttonList[selection].split(`"`)[1],
                    canceled: canceled
                }
                return def(e);
            }
        }
    }
    
}