'use strict';

angular.module('cs.create-state', ['cs.tree', 'cs.create-service'])
.controller('StateController', ['$scope', 'toaster','csApi', function($scope, toaster, csApi) {

	var newStateId;

	$scope.dateObject = {
		date: "",
		time: ""
	};
	$scope.properties = ['', 'session_id',
		'interaction_id', 'application_type',
		'application_id', 'resource_type',
		'resource_id', 'media_type',
		'est_duration', 'timestamp'
	];
	$scope.propertyInputs = [];
	$scope.usedProperties = [];
	$scope.propertyValues = [];
	$scope.keyInputs = [];
	$scope.customKey = [];
	$scope.uniqueTemplate = '';
	$scope.allowedKeys = [];
	$scope.customKeyValues = [];
	$scope.inputNumber = 0;
	$scope.title = 'Add State';
	$scope.typeTitle = 'State Type';
	$scope.panelId = 'State';
	$scope.valid = true;
	$scope.tz = new Date().toString().match(/(\(\w*[\s+\w+]*\)+)/g) ? new Date().toString().match(/(\(\w*[\s+\w+]*\)+)/g)[0] : '';

	$scope.getTimeStamp = function(){
		if($scope.isValidDate()){
			var time = $scope.dateObject.time.split('.');
			time[0] = parseInt(time[0]);
			time[1] = parseInt(time[1]);

			//uses military time, no PM
			// if (time[2] === 'PM') {
			// 	time[0] += 12;
			// }
			var date = $scope.dateObject.date;
			date.setHours(time[0]);
			date.setMinutes(time[1]);
			return date;
		} else { return null; }
	};

	$scope.isValidDate = function(){
		return angular.isDate($scope.dateObject.date);
	};

	$scope.startEntity = function() {
		var i;
		var jsonService = {
			'state_type': $scope.tabData.entityType
		};
		$scope.createFeedback = null;
		for (var attr in $scope.usedProperties) {
			jsonService[attr] = $scope.usedProperties[attr];
		}
		
		jsonService["timestamp"] = $scope.getTimeStamp();
		
		if ($scope.customKey.length > 0) 
			jsonService["customstart"] = {}; 
			
		for (i = 0; i < $scope.customKey.length; i++) {
			if ($scope.customKey[i] && $scope.customKeyValues[i]) {
				jsonService["customstart"][$scope.customKey[i]] = $scope.customKeyValues[i];
			}
		}
		csApi.startState($scope.baseUrl, $scope.tabData.node.service_id, jsonService).then(successCallback, errorHandler);
	};

	//error callback
	function errorHandler (httpResponse) {
		toaster.pop('error', 'Failed to create state', 'Server responded with status: ' +
			httpResponse.status + ' (' + httpResponse.statusText + ')');
		$scope.valid = false;
		$scope.addHttpRequestHistory(httpResponse, 'Start State');
	}

	function successCallback (httpResponse) {
		$scope.addHttpRequestHistory(httpResponse, 'Start State');
		//for selecting the service and the new state after creation
		$scope.tabData.selectOnRefresh = {
			serviceId: $scope.tabData.node.service_id,
			stateId: httpResponse.data.state_id,
			taskId: null
		}

		toaster.pop('success', 'State created successfully');
		$scope.tabData.queryById($scope.tabData.oldQueryType, $scope.tabData.oldCustomerId);
		// $scope.$apply();
	}

	$scope.getKeys = function() {
		var key;
		for (key in $scope.tabData.stateAttributes) {
			$scope.allowedKeys.push(key);
		}
	}

	$scope.getBusinessAttributes = function() {
		$scope.businessAttributes = $scope.tabData.stateAttributes;
	}

}]);
