const setinit_regex = /(?:State\.variables\.)?([a-zA-Z0-9\[\]'"\-_\$\.]+)\s*([+\-\*=]+)\s*(.*)/;

Macro.add('setinit', {
	skipArgs : true,
	handler  : function () {
		try {

            let assignment = this.args.full;
            let treffer = assignment.match(setinit_regex);
            let varname = '$'+treffer[1];

            createArrOnDemand(varname);
            Scripting.evalJavaScript(assignment);

		}
		catch (ex) {
			return this.error('bad setinit expression: ' + ex.message);
		}
	}
});

window.createArrOnDemand = function(varname){
    let varnameLayers = varname.split("[")
    let currentLayer = varnameLayers[0];
    for(let i = 0; i < varnameLayers.length - 1; i++){
        let index = varnameLayers[i+1].substring(0, varnameLayers[i+1].length - 1);
        if(!State.getVar(currentLayer))
        {
            if(/^\+?(0|[1-9]\d*)$/.test(index))
                State.setVar(currentLayer,[]);
            else
                State.setVar(currentLayer,{});
        }
        currentLayer += "["+varnameLayers[i+1];
    }
}

window.setvar = function(varname,value){
    if(typeof varname !== "string"){
        console.error("Unsupported variable name type in setvar:",varname,value);
        return false;
    }
    if(varname.length == 0){
        console.warn("Empty variable name in setvar:",varname,value);
        return false;
    }
    if(varname[0] != '$'){
        console.warn("Call of setvar with var name that isnt lead by $:",varname,value);
        varname = '$'+varname;
    }
    createArrOnDemand(varname);
    if(!State.setVar(varname,value)){
        console.error("Failed to set var in setvar:",varname,value);
        return false;
    }
    return true;
}


Macro.add('setn', {
	skipArgs : true,
	handler  : function () {
		try {

            let assignment = this.args.full;
            let treffer = assignment.match(setinit_regex);
            let varname = '$'+treffer[1];

            if(!State.getVar(varname))
                State.setVar(varname,0)
            Scripting.evalJavaScript(assignment);

		}
		catch (ex) {
			return this.error('bad setinit expression: ' + ex.message);
		}
	}
});

Macro.add('sets', {
	skipArgs : true,
	handler  : function () {
		try {

            let assignment = this.args.full;
            let treffer = assignment.match(setinit_regex);
            let varname = '$'+treffer[1];

            if(!State.getVar(varname))
                State.setVar(varname,'')
            Scripting.evalJavaScript(assignment);

		}
		catch (ex) {
			return this.error('bad setinit expression: ' + ex.message);
		}
	}
});
