/*
 *	IT-Services der Sozialversicherung GmbH
 *	Software Operations
 *	Software Quality Assurance
 *
 *	PRODUCT:	CCDB - Command and Control Database
 *	MODULE:		sheetform.js
 *	VERSION:	0.8.0.99
 *	AUTHOR:		WSC - Wolfgang Scherer
 *	HISTORY:
 *  Version    | Date       | Description
 * ------------+------------+---------------------------------------------------
 * 00.08.00.99 | 2015-12-04 | cloned from queryparamforms.js
 * ------------+------------+---------------------------------------------------
 *
 */
 
console.log("sheetform loaded");

var sheetform_version = '00.08.01.00';

var forms = {};

// synchronization of text input and drop-down select for 'presets' input
// this function is used as onChange()-handler of the select-part of the presets fieldset
function combo(thelist, theinput) {
    theinput = document.getElementById(theinput);
    var idx = thelist.selectedIndex;
    var content = thelist.options[idx].innerHTML;
    theinput.value = content;
}


// make <o> to something displayable
function makeString(o) {
	var ts = typeof o;
	switch (ts) {
		case 'number':
		case 'string':
		case 'boolean':
			return o;
			break;
		default:
			return '['+ts+']';
	}
}

// create a visual presentation of <obj> and insert it into <parent>
function insert_doctable(parent,obj) {
	var ftab;
	var tn;
	if (typeof obj === 'object') {
		ftab = document.createElement('table');
		ftab.style.border = "1px solid black";
		ftab.style.borderCollapse = "collapse";
		var frow = ftab.insertRow(-1);
		var fnc = frow.insertCell(-1);
		var fvc = frow.insertCell(-1);
		tn = document.createTextNode("Name");
		fnc.style.fontWeight = "bold";
		fnc.style.border = "1px solid black";
		fvc.style.border = "1px solid black";
		fnc.appendChild(tn);
		tn = document.createTextNode("Wert");
		fvc.style.fontWeight = "bold";
		fvc.appendChild(tn);
		for (fd in obj) {
			frow = ftab.insertRow(-1);
			fnc  = frow.insertCell(-1);
			fvc  = frow.insertCell(-1);
			fnc.style.border = "1px solid black";
			fvc.style.border = "1px solid black";
			fnc.style.verticalAlign = "top";
			fnc.appendChild(document.createTextNode(fd));
			insert_doctable(fvc,obj[fd]);
		}
	} else {
		ftab = document.createElement('p');
		tn = document.createTextNode(makeString(obj));
		ftab.appendChild(tn);
	}
	parent.appendChild(ftab);
}	

//
// =========================== sheet forms handling ==================================================
//

//
// anchor elements provide the link between the DOM and the formdata structure(s)
//
var anchorElements = {};

/* *****************************************************************************
 *	FUNCTION:	createAnchorElement
 *	INPUT:		etyp	-	HTML element type string 
 *				fdo		-	the forms data object in the forms data object tree got from the server
 *							this is a reference to a [paraminfo] object
 *				eid		-	the ID the HTML element created shall receive
 *	RETURNS:	aeo	-	anchor element object:
 *					id	- 	the DOM ID of the created HTML element / anchor element for <fdo>
 *							this is usually equal to <eid>, but should not be depended on
 *					el	-	DOM handle to created element
 *					ael	-	handle to anchor element
 *	DESCRIPTION:	creates an HTML element with its according entry in the <anchorElements> dictionary
 *					this allow to find the forms data entry in element event handling functions
 */
function createAnchorElement(etyp,fdo,eid) {
	var el = document.createElement(etyp);
	el.setAttribute("id",eid);
	if (anchorElements[eid]) {
		console.error("AnchorElementsError: element with ID "+eid+" is an already existing anchor element");
	}
	anchorElements[eid] = {};					// create the anchor element with the name <eid>
	anchorElements[eid].formDataObject = fdo;
	return {id: eid, el: el, ael: anchorElements[eid]};
}

function getAnchorElement(id) {
	if (!anchorElements[id]) {
		console.error("AnchorElementsError: there is no anchor element with id "+id);
		console.log("Present anchor elements are: ",anchorElements);
	}
	return anchorElements[id];
}

//
// atomic inputs 
//

/* *****************************************************************************
 *  FUNCTION:       createStringInput
 *  INPUT:          formid      -   HTML ID of the encompassing <form> element
 *                  fdo         -   the FormData object input is to be created for
 *                  idprefix    -   prefix to be set before IDs of the created HTML elements
 *  DESCRIPTION:    create an input element to enter data for 'String' item
 *                  creates a text input HTML element for arbitrary values
 */
function createStringInput(formid,fdo,idprefix) {
	myid = idprefix+'.'+fdo.name;
	var aeo = createAnchorElement('input',fdo,myid);
	aeo.el.setAttribute("type","text");
	aeo.el.setAttribute("name",myid);
	aeo.ael.formDataObject = fdo;
	aeo.ael.formid = formid;
	aeo.ael.idprefix = idprefix;
	if (fdo.maxlen) aeo.el.setAttribute("size",pdo.maxlen);
	if (fdo.value) {
		if (typeof(pdo.value)==='string') {
			aeo.el.setAttribute("value",fdo.value);
		} else {
			console.error("Illegal value type "+typeof(fdo.value)+" for string input: ",fdo.value);
		}
	}
	return aeo.el;
}	
	
/* *****************************************************************************
 *  FUNCTION:   createFormInput
 *  INPUT:      formid      -   HTML ID of the encompassing form
 *              fdo         -   FormData object input is to be created for
 *              idprefix    -   prefix to be set before created IDs for input elements
 *  RETURNS:    a <tr> element to be appended to a table
 *  DESCRIPTION:    create the input elements for one data object <fdo>
 *                  each input is created as a row to a containing table
 *                  each row has 2 cells: 
 *                      the label cell, containing the label for the input
 *                      the value cell, containing the input element(s) for the item <fdo>
 */ 
function createFormInput(formid,fdo,idprefix) {
	console.log("createFormInput.name="+idprefix+'.'+fdo.name);
	var tr = document.createElement('tr');
	// first the label
	var lab = document.createElement('label');
	var ltx = document.createTextNode(fdo.attributes?fdo.attributes.labeltext:null || fdo.labeltext || fdo.typetext || fdo.name);
	lab.setAttribute("title",pdo.attributes?pdo.attributes.typedesc:null || pdo.typedesc);
	lab.appendChild(ltx);
	// then the input(s) for the value
	var inp = createStringInput(formid,fdo,idprefix);
	var lc = tr.insertCell(0);  // the "label cell"
	lc.appendChild(lab);
	var vc = tr.insertCell(-1); // the "value cell"
	vc.appendChild(inp);
	return tr;
}

/* *****************************************************************************
 *  FUNCTION:   build_sheet_form
 *  INPUT:          sdata   -   a worksheet object:
 *                      attributes:
 *                      !ref    -   sheet range in Excel A1:A1 format
 *                      !range  -   sheet range in [range] format:
 *                          s   -   start of range:
 *                              r   -   start row 0..n
 *                              c   -   start column 0..n
 *                          e   -   end of range:
 *                              r   -   end row 0..n
 *                              c   -   end column 0..n
 *                      <cellname>  -   a cell, where <cellname is in Excel A1 format
 *                  formid  -   ID of <form> element into which all the inputs are to be placed
 *  DESCRIPTION:    build up the html for the sheet form
 *                  the <form> element is created with ID <formid>
 */
function build_sheet_form(sdata,formid) {
	var f = document.getElementById(formid);
	forms[formid] = {};
	forms[formid].fdata = fdata;
	var dt = document.getElementById(doctableid);
	console.log("build_sheet_form.sdata: ",sdata);
	var form = document.createElement('form');
	form.setAttribute("enctype","multipart/form-data");
	form.setAttribute("action",sdata.url);
	form.setAttribute("method","POST");
	form.setAttribute("id",formid);
	var submitbutton = document.createElement("input");
	submitbutton.setAttribute("type","submit");
	submitbutton.setAttribute("id",formid+"_submit");
	submitbutton.setAttribute("value",(fdata.reqtype?fdata.reqtype:"Aktion")+" starten");
	form.appendChild(submitbutton);
	if (fdata.dataname) {
		var dnf = document.createElement("input");
		dnf.setAttribute("type","hidden");
		dnf.setAttribute("id","dataname");
		dnf.setAttribute("name",formid+".dataname");
		dnf.setAttribute("value",fdata.dataname);
		form.appendChild(dnf);
	}
	// console.log("sdata: ",sdata);
    var sheetrange = null; 
    var fep = null;
    if (sdata["!ref"]) {
    }
    if (!sheetrange) {
    }
    if (!sheetrange) {
        sheetrange = {s: {r: 0, c: 0}, e: {r: 9, c: 9}};
    }
    for (var cr=sheetrange.s.r; cr<=sheetrange.e.r; cr++) {
        for (var cc=sheetrange.s.c; cc<=sheetrange.e.c; cc++) {
            fp = createStringInput(formid,fdata,formid);
            form.appendChild(fp);
        }
    }
	f.appendChild(form);
}