﻿// namespace atlas
var atlas = atlas || {};

/**
 * class BenchmarkTool
 *
 * This class encapsulates the selections made by the user as they 
 * progress through the steps of the wizard.
 */
atlas.BenchmarkToolConfig = function() {

	// copy for closure
	var self = this;

	//// Private vars ////
	// In form:
	// var _memberVar;

	//// Private functions ////
	this.loadLocations = function(locIds, onLoadComplete, onSuccess) {

		$(locIds).each(function(index, id) {
			var obj = { id: "" + id, name: "Loading...", type: "Loading...", typeId: "Loading..." };
			pub.locations.push(obj);
		});

		self.queryLocations(locIds, function(result) {
				var resultArray = JSON.parse(result.d);

				for (var i = 0; i < resultArray.length; i++) {
					//replace the object in the locations array with the result obj that matches the id
					var resultObj = resultArray[i];
					var index = -1;
					$(pub.locations).each(function(j, obj) {
						if (obj.id == resultObj.id) {
							index = j;
							return false;
						}
					});
					if (index > -1) {
						pub.locations.splice(index, 1, resultObj);
					}
				}

				if (onLoadComplete) {
					onLoadComplete();
				}
			}
		);
	};

	this.loadBenchmarkLocation = function(locId, onLoadComplete) {
		pub.benchmarkLocation = { id: "" + locId, name: "Loading...", type: "Loading...", typeId: "Loading..." };

		self.queryLocations([locId], function(result) {
			var resultArray = JSON.parse(result.d);
			if (resultArray.length == 0) {
				return;
			}
			pub.benchmarkLocation = resultArray[0];

			if (onLoadComplete) {
				onLoadComplete();
			}
		});
	};

	this.queryLocations = function(locIds, onSuccess) {
		//only the ID is available in the query string, but we want to be able to display
		//name, types, etc as well, so query the web service to get that info
		var parms = JSON.stringify({
			ids: locIds
		});

		$.ajax({
			type: "POST",
			url: "/Services/EntitySearch.asmx/FindLocations",
			data: parms,
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert("Error connecting to service.\n\n" + textStatus);
			},
			success: onSuccess
		});
	};
	
	//// Public variables & methods ////
	var pub = {

		//// Public variables ////
		// list of DatacenterContainers, one for each indicator chosen
		containers: [],

		// list of locations to be compared to the benchmark location
		locations: [],

		// The benchmark location. This location provides the baseline for scaling 
		// the values of the other regions being compared to this one.
		benchmarkLocation: { id: 0, name: "" },

		//// public functions ////
		/**
		* Serializes the current configuration to a NameValueCollection suitable
		* for conversion a query string
		*/
		toNameValueCollection: function() {

			var qs = new velir.collections.NameValueCollection();

			// indicator containers
			for (var i in _indicatorSelector.indContainers) {
				qs.add(atlas.BenchmarkToolConfig.paramContainer, _indicatorSelector.indContainers[i].toQueryString());
			}

			// locations
			for (var i in this.locations) {
				qs.add(urlParams.locationId, this.locations[i].id);
			}

			// benchmark location
			qs.add(atlas.BenchmarkToolConfig.paramBenchmarkLocation, this.benchmarkLocation.id);

			return qs;
		},

		/**
		* Serializes the current configuration to a query string
		*/
		toQueryString: function() {
			return this.toNameValueCollection().toQueryString();
		},

		/**
		* Parses configuration from a query string and sets BenchmarkTool properties
		*/
		fromQueryString: function(queryString, onContainerLoadComplete, onLocationsLoadComplete, onBenchmarkLocationLoadComplete) {
			var qs = velir.collections.NameValueCollection.parseQueryString(queryString);

			// indicator containers
			var value = qs.getValue(atlas.BenchmarkToolConfig.paramContainer);
			var values = value == null ? [] : value.split(",");
			for (var i in values) {
				var containerConfig = values[i];
				var container = velir.datacenter.DatacenterContainer.parseQueryString(containerConfig, onContainerLoadComplete);
				this.containers.push(container);
			}

			// locations
			value = qs.getValue(urlParams.locationId);
			var values = value == null ? [] : value.split(",");
			self.loadLocations(values, onLocationsLoadComplete);

			// benchmark location
			var blocId = qs.getValue(atlas.BenchmarkToolConfig.paramBenchmarkLocation);
			if (blocId != null) {
				pub.benchmarkLocation = { id: blocId, name: "Loading..." };
				self.loadBenchmarkLocation(blocId, onBenchmarkLocationLoadComplete);
			}
		},

		/**
		* Returns true if the BenchmarkTool has been configured with all the necessary 
		* information to display a report
		*/
		isConfigured: function() {
			var b = _indicatorSelector.indContainers.length > 0 &&
				   this.locations.length > 0 &&
				   this.benchmarkLocation.id > 0;
			return b;
		}

	};

	return pub;
}

//// Static vars and functions ////

// URL parameters specific to the BenchmarkTool
atlas.BenchmarkToolConfig.paramContainer = "cont";
atlas.BenchmarkToolConfig.paramBenchmarkLocation = "bloc";

/**
 * Parses a query string into a new BenchmarkTool
 * 
 * @returns A new BenchmarkTool containing the parsed query string.
 */
atlas.BenchmarkToolConfig.parseQueryString = function(queryString, onLoadComplete, onLocationsLoadComplete, onBenchmarkLocationLoadComplete) {
	var tool = new atlas.BenchmarkToolConfig();
	tool.fromQueryString(queryString, onLoadComplete, onLocationsLoadComplete, onBenchmarkLocationLoadComplete);
	return tool;
}	
