'use strict';

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

	var newServiceId;

	$scope.properties = [
		'',
		'session_id',
		'interaction_id',
		'application_type',
		'application_id',
		'resource_type',
		'resource_id',
		'media_type',
		'est_duration',
		'timestamp'
	];
	$scope.allowedKeys = [];
	$scope.propertyInputs = [];
	$scope.usedProperties = [];
	$scope.propertyValues = [];
	$scope.keyInputs = [];
	$scope.customKey = [];
	$scope.customKeyValues = [];
	$scope.timestamp;
	$scope.serviceOptions = ['Customer ID', 'Anonymous Contact ID'];
	$scope.inputNumber = 0;
	$scope.title = 'Start New Service';
	$scope.typeTitle = 'Service Type';
	$scope.panelId = 'Service';
	$scope.uniqueURL = 'app/modules/context-services/service.html';
	$scope.valid = true;
	$scope.tz = new Date().toString().match(/(\(\w*[\s+\w+]*\)+)/g) ? new Date().toString().match(/(\(\w*[\s+\w+]*\)+)/g)[0] : '';

	$scope.dateObject = {
		date: "",
		time: ""
	};

	$scope.getTimeStamp = function(){
		if($scope.isValidDate()){
			var time = $scope.dateObject.time.split('.');
			time[0] = parseInt(time[0]);
			time[1] = parseInt(time[1]);
			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 = {
			'service_type': $scope.tabData.entityType
		};

		$scope.valid = true;
		$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];
			}
		}

		if ($scope.idType === 'Customer ID') {
			csApi.startCustomerService($scope.baseUrl, $scope.contactId, jsonService).then(successCallback, errorHandler);
		} else {
			csApi.startAnonymousService($scope.baseUrl, $scope.contactId, jsonService).then(successCallback, errorHandler);
		}
	};

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

	function successCallback (httpResponse) {
		$scope.addHttpRequestHistory(httpResponse, 'Start Service');

		//selects the new service after creation
		$scope.tabData.selectOnRefresh = {
			serviceId: httpResponse.data.service_id,
			stateId: null,
			taskId: null
		}
		
		toaster.pop('success', 'Service created successfully');
		$scope.tabData.queryById($scope.tabData.oldQueryType, $scope.tabData.oldCustomerId);
	}

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

	$scope.getBusinessAttributes = function() {
		$scope.businessAttributes = $scope.tabData.serviceAttributes;
	}
}])
.filter('excludeUsed', function() {
	return function(input, scope) {
		var i,
			j,
			output = [],
			used;
		for (i = 0; i < input.length; i++) {
			used = false;
			if (input[i] === '' && (scope.$last)) {
				used = true;
			} else {
				for (j = 0; j <= scope.$index; j++) {
					if (input[i] === scope.usedProperties[j] && j !== scope.$index) {
						used = true;
						break;
					}
				}
			}
			if (!used) {
				output.push(input[i]);
			}
		}
		return output;
	};
})
.directive('createitem', function() {
	return {
		templateUrl: 'app/modules/context-services/create.html',
		restrict: 'E',
		transclude: 'true',
		link: function(scope, ele) {
			scope.getAllowedKeys = function() {
				if (scope.allowedKeys.length != 0) {
					scope.getKeys();
				}
				return scope.allowedKeys;
			};

			scope.getAttribute = function() {
				if (!scope.businessAttributes) {
					scope.getBusinessAttributes();
				}
				return scope.businessAttributes;
			};

			scope.startIfEnter = function(event) {
				if (event.keyCode === 13) {
					scope.startEntity();
				}
			};

			scope.initSelectButton = function(){
				if(scope.getAllowedKeys().length > 0){
					scope.entityType = scope.getAttribute()[scope.getAllowedKeys()[0]];
				}
			};
		}
	};
})
.directive('propertyinfo', function() {
	return {
		link: function(scope, ele) {
			scope.$watchCollection(function() {
                            console.log('property changed');
                            console.log($('button[ark-select]'));
				return $('button[ark-select]');
			}, function() {
				var lastIndex = scope.$parent.$$childTail.$index;
				if (scope.$last || (scope.$index + 1 === lastIndex && lastIndex !== scope.properties.length - 1)) {
					ele.prop('disabled', false);
				} else {
					ele.prop('disabled', true);
				}
			});

		}
	};
}).directive('uniqueelements', function($compile, $http) {
	return {
		restrict: 'E',
		link: function(scope, ele) {
			if (scope.uniqueURL) {
				$http.get(scope.uniqueURL).then(function(response) {
					let html = response.data;
					ele.replaceWith($compile(html)(scope));
				});
			}
		}
	};
});
