// Controller for the statistic handling in "cfutablet" Widget.
var statCFUData = (function($) {

	var connectorClient = qmatic.connector.client;
 	var wwClient = qmatic.webwidget.client;

	var branchVariable;
	var currentDate;
	var markNames = [];

	function updateBranchVariable(serviceId, markName, waitingTime) {
		loadBranchVariable(serviceId);
		addToBranchVariable(currentDate, markName, waitingTime);
		saveBranchVariable(serviceId);
	}
	
	
	function addToBranchVariable(date, markName, waitingTime) {
		initBranchVariable(date);
		addDataToBranchVariable(date, markName, waitingTime);		
	}
	
	function addDataToBranchVariable(date, markName, waitingTime) {
		branchVariable[date][markName].totWaiting += waitingTime;
		branchVariable[date][markName].visits += 1;
	}
	
	function initBranchVariable(date) {
		if(typeof branchVariable == 'undefined') {
			branchVariable = {};
		}
		initDate(date);
		for(var i=0;i<markNames.length;i++) { //init for all marks in order for all to show in statistics
			var markNameItem = markNames[i];
			initMarkOnDate(date, markNameItem);
		}
	}

	
	function initDate(date) {
		if(!branchVariable.hasOwnProperty(date)) {
			branchVariable[date] = {};
		}
	}
	
	function initMarkOnDate(date, markName) {
		if(!branchVariable[date].hasOwnProperty(markName)) {
			branchVariable[date][markName] = {
				'visits' : 0,
				'totWaiting' : 0
			}
		}
	}	

	function loadBranchVariable(serviceId) {
		var branchId = wwClient.getBranchId();
		var variableName = getBranchVariableName(serviceId);
		var storedBranchVar = getBranchVariableIfAvailable(branchId, variableName);
		if(typeof storedBranchVar !== 'undefined') {
			var storedValue = storedBranchVar.value;
			removeEscaping(storedValue);
			storedValue = restoreRealNames(storedValue);
			branchVariable = JSON.parse(storedValue);
			resetBranchVariablesIfNewDate(branchId);
		} else {
			branchVariable = {};
		}
	}
	
	function restoreRealNames(json) {
		json = json.replace(/"v"/g, '"visits"');
		json = json.replace(/"t"/g, '"totWaiting"');
		return json;
	}
	
	function resetBranchVariablesIfNewDate(branchId) {
		if(!branchVariable.hasOwnProperty(currentDate)) {
			branchVariable = {};
			resetBranchVariableForAllUnits(branchId);
		}
	}
	
	
	function resetBranchVariableForAllUnits(branchId) {
		var allBranchVariables = connectorClient.getBranchVariables(branchId);	
		for(var i=0;i<allBranchVariables.length;i++) {
			if(isBranchVariableCfuGraph(allBranchVariables[i])) {
				deleteBranchVariable(branchId, allBranchVariables[i].name);
			}
		}
	}

	function isBranchVariableCfuGraph(branchVariable) {
		return branchVariable.name.indexOf('cfuScore') == 0;
	}
	
	function deleteBranchVariable(branchId, variableName) {
		connectorClient.deleteBranchVariable(branchId, variableName);
	}
	
	/* returns undefined if no match */
	function getBranchVariableIfAvailable(branchId, variableName) {
		var allBranchVariables = connectorClient.getBranchVariables(branchId);
		for(var i=0;i<allBranchVariables.length;i++) {
			if(allBranchVariables[i].name == variableName) {
				return allBranchVariables[i];
			}
		}
	}
	
	/* unused, should be used for performance but currently gives error if unavailable */
	/*function getBranchVariable(branchId, variableName) {
		return connectorClient.getBranchVariable(branchId, variableName);
	}*/
	
	function removeEscaping(value) {
		value.replace('\\"', '"');
	}
	
	function saveBranchVariable(serviceId) {
		var variableName = getBranchVariableName(serviceId);
		var branchId = wwClient.getBranchId();
		var json = JSON.stringify(branchVariable);
		json = shrinkJson(json);
		return connectorClient.setBranchVariable(branchId, variableName, json);
	}
	
	function shrinkJson(json) { //temp fix
		json = json.replace(/visits/g, "v");
		json = json.replace(/totWaiting/g, "t");
		return json;
	}
	
	function getBranchVariableName(serviceId) {
		return 'cfuScore' + serviceId;
	}	

	/* public content */
	return {
	
		/* updated on visit-call event */
		setCurrentDate : function(date) {
			currentDate = date;
		},
		/* updated on visit-call event */
		setMarkNames : function(names) {
			markNames = names;
		},
	
		/* update on CFU-vote */
		updateMarkVariable : function(serviceId, markName, waitingTime) {
			serviceId = parseInt(serviceId, 10);
			waitingTime = parseInt(waitingTime, 10);
			if(!isNaN(serviceId) && !isNaN(waitingTime)) {
				updateBranchVariable(serviceId, markName, waitingTime);
			} else {
				wwClient.logError("Unable to store statistic for mark : " + markName);
			}
		}
	};
})(jQuery);