import { StandardLabel } from '/sd:standard-label.js'; 
import { ModbusRequestContainer } from '/sd:modbus-request-container.js'; 
import { ActionButton } from '/sd:action-button.js'; 
//
// Common declaration of global variables
//


export class CommonIncludes {	

	/**
	 * function reads choosen container properties of template from config XML file and invoke callback function of proper container
	 * @param {*} containerSettings 
	 * @param {*} nameOfContainer 
	 * @param {*} callbackFoundHtmlContainer 
	 * @param {*} callbackAttributes 
	 * @param {*} parentNode 
	 */
	static checkContainerAndReadProperties(containerSettings, nameOfContainer, callbackFoundHtmlContainer, callbackAttributes = true, parentNode = "site", additionalArgument=null) {
		if(Math.round(containerSettings.length) > 0) {
			var objectWithProperParentFound = false;
			for(var i = 0; i < Math.round(containerSettings.length); i++) {
				if(containerSettings[i].parentNode.localName.toLowerCase() == parentNode.toLowerCase()) {
					callbackFoundHtmlContainer((callbackAttributes) ? containerSettings[i].attributes : containerSettings, additionalArgument);
					objectWithProperParentFound = true;
					break;
				}
				else
					console.log("'" + nameOfContainer + "' XML object found inside bad parent: '" + containerSettings[i].parentNode.localName + "'. Searching for nextone.");
			}
			if(objectWithProperParentFound) {
				if(Math.round(containerSettings.length) > 1) {
					console.log("More than one '" + nameOfContainer + "' found in XML file!!! Settings of firstone with proper parent was taken.");
				}
			}
			else
				console.log("There was no '" + nameOfContainer + "' XML object with proper parent!!!");
		}
		else
			console.log("No '" + nameOfContainer + "' found in XML file!!!");
	}

	/**
	 * callback function reads dateTimeContainer properties of template from config XML file and it create this container(with these values) in HTML file. It creates logout button and date time widget inside the continer 
	 * @param {jQuery} xmlObject 		Collection of dateTimeContainer markup read from XML file
	 */
	static dateTimeContainerProperties(xmlObject, data) {
		//logoutButton
		var buttonXmlObject = xmlObject.find("logoutButton");
		var objPointer = new ActionButton(buttonXmlObject, "dateTimeContainer", "CommonIncludes.DeleteCookie('sid');");
		
		objPointer.setLabelText(window.choosenLexicon.getLexiconMarkupText("logoutButtonLabel") + data.userName);
		data.buttons.push(objPointer);
		
		//dateTime text
		var dateTimeXmlObject = xmlObject.find("dateTime");
		objPointer = new StandardLabel(dateTimeXmlObject, "dateTimeContainer", "BasicContainer", null, "dateTime");
		
		data.dateTimePoints.push(objPointer);
		var newElement = data.dateTimePoints[data.dateTimePoints.length - 1];
		newElement.setTextValue((data.clockMode == 12) ? "1970.01.01 12:00:00 AM" : "1970.01.01 00:00:00");
		
		//add binding time
		var pointRefreshFrequency = dateTimeXmlObject[0].attributes['pointRefreshFrequency'].value;
		window.modbusReader[ModbusRequestContainer.findModbusNetworkIndex(pointRefreshFrequency, window.modbusReader)].initRegister("time", newElement);
	}
	
	/**
	 * callback function reads properties of template from config XML file and it create this container(with these values) in HTML file. It creates image with hyperlink inside the continer
	 * @param {jQuery} attributes 		Attributes of choosed markup read from XML file
	 */
	static imageWithHyperlinkContainerProperties(attributes, containerProperties) {
		var parentObj = document.getElementById(containerProperties.parentId);
		//create link
		if(attributes['link'] != undefined && attributes['link'].value != "") {
			if(containerProperties.type == "onclick") {
				parentObj.setAttribute("onclick", attributes['link'].value);
			}
			else if(containerProperties.type == "a") {
				var linkImage = document.createElement("a");
				linkImage.setAttribute("id", containerProperties.id + "Link");
				linkImage.setAttribute("href", attributes['link'].value);
				parentObj.appendChild(linkImage);
			}
			else {
				console.log("Type(" + containerProperties.type + ") is not supported by CommonIncludes.imageWithHyperlinkContainerProperties() !!!");
			}
		}
		//create image
		var image = document.createElement("img");
		image.setAttribute("id", containerProperties.id);
		image.setAttribute("src", window.location.protocol + "//" + window.location.host + "/sd:" + themeName + "_" + attributes['fileName'].value);
		image.setAttribute("alt", containerProperties.alt);
		//insert image to link or to parent container
		if(containerProperties.type == "onclick" || attributes['link'] == undefined || attributes['link'].value == "") {
			parentObj.appendChild(image);
		}
		else if(attributes['link'] != undefined && attributes['link'].value != "" && containerProperties.type == "a") {
			linkImage.appendChild(image);
		}
	}

	//callback function reads numericPointsHeaderContainer label of template from config XML file and it create this container(with label) in HTML file.
	static headerContainerProperties(xmlObject, pointProperties) {
		var objPointer = null;
		if(xmlObject[0].attributes['label'] != undefined && xmlObject[0].attributes['label'].value != null && xmlObject[0].attributes['label'].value != "") {
			objPointer = new StandardLabel(xmlObject, pointProperties.parentId, "HeaderLabel", pointProperties.itemNumber, pointProperties.id, true);
			objPointer.setTextValue(xmlObject[0].attributes['label'].value);
		}
		else if(pointProperties.label != undefined && pointProperties.label != null && pointProperties.label != "") {
			objPointer = new StandardLabel(xmlObject, pointProperties.parentId, "HeaderLabel", pointProperties.itemNumber, pointProperties.id, true);
			objPointer.setTextValue(pointProperties.label);
		}
		else {
			objPointer = document.getElementById(pointProperties.parentId);
			objPointer.setAttribute("style", "display: none;");
		}
	}

	/**
	 * callback function reads topTextContainer properties of template from config XML file and it create this container(with these values) in HTML file. It puts title of view inside the continer
	 * @param {jQuery} attributes 			Attributes of topTextContainer markup read from XML file
	 * @param {String} labelAttributeName	Attribute name of the label
	 */
	static topTextContainerProperties(attributes, labelAttributeName) {
		var parentObj = document.getElementById("topTextContainer");
		var topTextLabel = document.createElement("span");
		topTextLabel.setAttribute("id", "topTextContainerLabel");
		parentObj.appendChild(topTextLabel);
		topTextLabel.innerHTML = attributes[labelAttributeName].value;
	}

	//function creates shared container for few containers
	static createSharedContainer(id, className, parentId) {
		var imgObj = document.createElement("div");
		imgObj.setAttribute("id", id);
		imgObj.setAttribute("class", className);
		var parentImgObj = document.getElementById(parentId);
		parentImgObj.appendChild(imgObj);
	}


	//function to logout from webSite of AAC20
	static DeleteCookie(cookie_id) {
		document.cookie = cookie_id + "=; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
		location.reload()
	}

	/**
	 * Returns value of choosen header, and formats values (if it is usr, then adds brackets, if it is priv, then converts to Int)
	 * @param {String} name		Name of header
	 * @returns {String}		Value of choosen header or if there is no choosen header, then resturns 101 (for priv), "" (for usr) or null for other cases
	 */
	static readHeader(name) {
		var text = document.cookie;
		var dataArray = text.split("; ");
		var keyAndValueArray;
		for(var i = 0; i < dataArray.length; i++) {
			keyAndValueArray = dataArray[i].split("=");
			if(name == keyAndValueArray[0]) {
				if(name == "usr")
					return " (" + keyAndValueArray[1] + ")";
				else if(name == "priv")
					return parseInt(keyAndValueArray[1]);
				else
					return keyAndValueArray[1];
			}
		}
		//if header wasn't found
		if(name == "usr")
			return "";
		else if(name == "priv")
			return 101;
		else
			return null;
	}
}