console.log("have been in WeBeans.class.js")

function webBeanLoaded(element) {
	if (document.weBeans == null) {
		class WeBeans {
			constructor() {
				this.debug=false;
			}
			
			lookup(id) {
				return this[id];
			}
			
			
			register(template) {
				var id = template.getAttribute("id");
				this[id] = new WeBean().init(template);
				this[id].overwriteBeans();
				
			}
			
			overwriteAllBeans() {
				for(var i in this) {
					var bean = this[i];
					if (bean instanceof WeBean) {
						bean.findBeans();
						bean.overwriteBeans();
					}	
				}
			}
						

		}
		
		class WeBean {
			constructor() {
				this.weBeanIdAttrubute = "data-is";
				this.weBeanDataAttrubute = "data-properties";
			}
			
			init(template) {
			//	uses a link from??the documents.links[], where all templates are registered.
			//	after this method was called, the linked template will be used for rendering
				this.id = template.getAttribute("id");
				this.component = template;
				this.componentName = "x-"+this.id;
				return this;

			}


			
			
			findBeans() {
				var nodes = document.evaluate("//div[@"+this.weBeanIdAttrubute+"='"+this.id+"']",document);
				var node = nodes.iterateNext();

				this.divs = [];

				while(node) {
					this.divs[this.divs.length]=node;
					node = nodes.iterateNext();
				}
				return this.divs;

			}


			overwriteBeans() {
				if (this.divs == null)
					this.findBeans();



				for(var i in this.divs) {
					var d = this.divs[i];
					
					if(d != null) {
					
						var data = JSON.parse(d.getAttribute(this.weBeanDataAttrubute));
						if (data == null)
							data = {};
						data.content = d.innerHTML;

						var properties = [];
						for(var i in data) { 
							properties[properties.length]=i; 
							if (data[i] == null)
								data[i] = "";
						}

						data.id=d.getAttribute("id");
						data.current = Structr.current;
						if (data.current.id == null)
							data.current.id = "";

						this.overwrite(d,data);
	//					if (SafetySwitch.check())
							document.weBeans.overwriteAllBeans()
					}
				}
			}
			
			
			
			getElement(id) {
				if (id.nodeName != null)
					return id;
				else
					return document.getElementById(id);
			}

			render() {
				return new Function("return `"+this.getComponent().innerHTML+"`;").call(this.data)
			}

			apply(id, data) {
				var element = this.getElement(id);
				if (data != null) this.data = data;
				element.innerHTML = this.render();
			}


			overwrite(id, data) {
				var element = this.getElement(id);
				if (data != null) this.data = data;
				element.outerHTML = this.render();
			}

			append(id, data) {
				var element = this.getElement(id);

				if (element == null) element = document.body;
				if (data != null) this.data = data;
				element.appendChild(document.createElement("div")).outerHTML = this.render();
			}


			replaceWithComponent(id,resetStyleInheritance, applyAuthorStyles) {
		   //     if (data != null) this.data = data;
				var element = this.getElement(id);
				
				var shadow = element.createShadowRoot();
				shadow.innerHTML = this.render();
				if (resetStyleInheritance == null) {
					shadow.resetStyleInheritance = true;
				} 
				else {
					shadow.resetStyleInheritance = resetStyleInheritance;
				}
				if (applyAuthorStyles == null) {
					shadow.applyAuthorStyles = false;
				} 
				else {
					shadow.applyAuthorStyles = applyAuthorStyles;
				}
			}

			getComponent() {
				if (this.component == null)
					this.component = document.getElementById(this.id);
				return this.component;
			}

			registerCustomTemplate(thisDoc) {
		//	initalizes the new template under: documents.links[componentName]
		//  the template can be used for rendering by: this.use(documents.links[componentName])


		//		var thisDoc = document.currentScript.ownerDocument;
				thisDoc.componentName = thisDoc.getElementsByTagName("template")[0].id;
				thisDoc.component = thisDoc.querySelector('#'+thisDoc.componentName);

				if (document.templates == null) document.templates = [];
				document.templates.push(thisDoc);
				document.templates[thisDoc.componentName] = thisDoc;

				var Panel = document.registerElement('x-'+thisDoc.componentName, {
				prototype: Object.create(HTMLElement.prototype, {
				  createdCallback: {
					value: function() {
					  var root = this.createShadowRoot();
					  var markup = new Function("return `"+thisDoc.component.innerHTML+"`;");
					  var data = JSON.parse(this.getAttribute("properties"));
					  data.content = this.innerHTML;
			//          var template = thisDoc.component;
					  var result = markup.call(data);
			//          var clone = document.importNode(template.content, true);
			//          var newNode = root.appendChild(clone);
					  this.shadowRoot.innerHTML = result;
					}
				  }
				})
			  });
			}

		}

			
		document.weBeans = new WeBeans();
	}
	
	var mode = null;
	
	var content = null;
	if (element.contentDocument != null) {
		mode="polyfill import by iframes";
		content = element.contentDocument
	}
	
	if (element.import != null) {
		mode="link rel=import";
		content = element.import
	}
	
	

	if (content != null) {
		var template = content.getElementsByTagName("template")[0];
		if (template != null) {
			document.weBeans.register(template);	
			element.setAttribute("id",template.getAttribute("id"));

			if (document.weBeans.debug)
				document.body.appendChild(document.createElement("div")).outerHTML= "<p>WebBean loaded "+element.id+" in mode: "+mode+"</p>";
		}
		else {
				document.body.appendChild(document.createElement("div")).outerHTML= "<p>Faile to load WebBean: "+element.id+" in mode: "+mode+"</p>";
		}
	}
}


window.webBeansInit = function webBeansInit() {
//	if(document.currentScript.ownerDocument == document) {
		// only entered in polyfillMode


		var links = document.getElementsByTagName("link");



	/*
		if (document.weBeans == null) {

			for (var i=0; i<links.length; i++) {
		//		element.append("\n"+links[i].outerHTML);
				if (links[i].getAttribute("rel") ==="import") 	
					document.body.appendChild(document.createElement("div")).outerHTML= '<iframe src="'+links[i].getAttribute("href")+'"  onload="javascript:webBeanLoaded(this)" hidden></iframe>';
			}

		}
		else {
	*/
	window.webBeansFound = false;
		for (var i=0; i<links.length; i++) {
		//		element.append("\n"+links[i].href);
	//			links[i].setAttribute("onload","javascript:webBeanLoaded(this)");
				if (links[i].getAttribute("rel") ==="import") {
					webBeanLoaded(links[i]);
					window.webBeansFound = true;
				}
	//		}

		}
	// bad Hack...: UcpComponentSupport.weBeanOnLoadListener completely unnessesary.
	// just defer app init until weBeans are found...
	// rewrite WebBeans as a pure class
	
		if (UcpComponentSupport.weBeanOnLoadListener["WebBeans"] != null) {
			UcpComponentSupport.done();
		}
	

//	}
};

window.webBeansInit();


if (!webBeansFound) {
	UcpComponentSupport.registerWeBeanOnLoadedListener("WebBeans",webBeansInit);
	if (TheSafetySwitch.check()) {
		console.log("No webeans found....try again");
		setTimeout(webBeansInit, 3000);
	}
}
