"use strict";

angular.module("ui.DH", [])
  .directive("dynheadingno", ['$injector',
    function ($injector) {
		return {
		restrict: "E",
			link: function (scope, element, attrs) {

				// update whenever indexed heading is changed
				attrs.$observe('headno', function(val){
					//console.log(val);
					var arrayHeadNo = parseHeadNo(val);
					buildHtmlElm(element, arrayHeadNo);
				});

			}
		};
	}]);

	// constructor for array of typed strings
	function cHeadNoObj (strProp, typeProp) {
		this.strProp = strProp;
		this.strType = typeProp
	}

	// parse indexed header and return an array of objects containing
	// the parts with their type e.g. 1.1.[1]. is 
	// the array: {"1.1.", false}, {"[1]", true}, {".", false} )	
	function parseHeadNo(strIn) {
		var arrayStrTyped = new Array();
		var inIndex = false;

		// parse the input string (string must be an indexed heading)
		var str = "";
		var i = 0;
		var c = strIn[i];
		do {
			if ( c == '[' || c == ']') {
				// close the inIndex... otherwise will step over the closed bracket
				if ( c == ']' ) {
					str += c;
					c = strIn[++i];
				}

				// str is the current part of the indexed heading and
				// inIndex specifies if it is a index or a normal part.
				var headNoObj = new cHeadNoObj(str, inIndex);
				arrayStrTyped.push(headNoObj);

				// now, toggle the type of the next part
				inIndex = inIndex == true ? false : true ;

				// reset str for the new object
				str = "";
			}

			str += c;
			c = strIn[++i];
		} while (i != strIn.length );

		// append the last object
		var headNoObj = new cHeadNoObj(str, inIndex);
		arrayStrTyped.push(headNoObj);

		return arrayStrTyped;
	}

	function buildHtmlElm(elem, arrayHeadNo) {
		elem.empty();

		var i;
		for ( i = 0; i < arrayHeadNo.length; i++ ) {
			var headNoObj = arrayHeadNo[i];
			var subElem;

			if (headNoObj.strType == false )
				subElem = document.createElement("label");
			else
				subElem = document.createElement("sub");

			subElem.innerHTML += headNoObj.strProp;
			elem.append(subElem);
		}
	}
