Ext.define("Portfolio.angular.Component", {

	xtype: "angular-component",

	extend: "Ext.Component",

	alias: [
		"widget.angular.component"
	],

	config: {
		rootTag: "app-root",
		appPath: "",
		baseHref: "/",
		mode: "dev"
	},

	renderTpl: [
		"<div id={id}-root data-ref=rootEl>",
		"</div>"
	],

	childEls: [
		{
			name: "rootEl",
			itemId: "root"
		}
	],

	alternateClassName: [
		"Ext.ux.angular.Component"
	],

	listeners: {
		afterrender: {
			fn: function(i_component) {

				var i_self = this;

				var i_root = i_self.rootEl;
				var i_domElement = i_root.dom;

				if (i_domElement.attachShadow) {

					var i_shadowRoot = i_domElement.attachShadow({
						mode: "open"
					});

					var s_mode = i_self.getMode() || "dev";

					var a_files = [
						i_self.getAppPath() + "/runtime.js"
					];

					if (!window.hasOwnProperty("Zone")) {
						a_files.push(i_self.getAppPath() + "/polyfills.js");
					}

					if (s_mode.toLowerCase() == "dev") {
						a_files.push(i_self.getAppPath() + "/vendor.js");
					}

					a_files.push(i_self.getAppPath() + "/main.js");

					var n_counter = a_files.length;

					var i_template = Ext.create("Ext.XTemplate",
						"<{rootTag} id={id}-root>",
							"<base id={id}-base href={baseHref}></base>",
						"</{rootTag}>"
					);

					var i_appRoot = Ext.DomHelper.createDom(i_template.apply({
						rootTag: i_self.getRootTag(),
						baseHref: i_self.getBaseHref(),
						id: Ext.id()
					}));

					var i_tag;

					if (s_mode === "dev") {

						i_tag = document.createElement("script");

						i_tag.setAttribute("type", "text/javascript");
						i_tag.async = false;
						i_tag.src = i_self.getAppPath() + "/styles.js";
					}
					else {

						i_tag = document.createElement("link");

						i_tag.setAttribute("rel", "stylesheet");
						i_tag.href = i_self.getAppPath() + "/styles.css";
					}

					i_shadowRoot.appendChild(i_tag);

					Ext.Array.each(a_files, function(s_path) {

						var i_script = document.createElement("script");

						i_script.setAttribute("type", "text/javascript");
						i_script.async = false;
						i_script.src = s_path;

						i_script.onload = function() {
							n_counter--;
							if (n_counter === 0) {

								i_shadowRoot.appendChild(i_appRoot);
							}
						};

						i_appRoot.appendChild(i_script);
					});

					i_root.appendChild(i_appRoot);
				}
				else {
					i_root.setText("This browser does not support shadow dom");
				}
			}
		}
	}
});
