'use strict';

angular.module('cs.complete', ['cs.tree'])
.controller('CompleteController', ['$scope', 'toaster', 'csApi', function($scope, toaster, csApi) {

	//var baseUrl = '/genesys/1/cs';

	var action;

	$scope.properties = [ '', 'session_id',
							'interaction_id', 'application_type',
							'application_id', 'resource_type',
							'resource_id', 'media_type',
							'est_duration', 'timestamp',
							'disposition', 'disposition_desc'];
	$scope.propertyInputs = [];
	$scope.usedProperties = [];
	$scope.propertyValues = [];
	$scope.keyInputs = [];
	$scope.customKey = [];
	$scope.customKeyValues = [];
	$scope.inputNumber = 0;
	$scope.completeForm = true;
	$scope.tz = new Date().toString().match(/(\(\w*[\s+\w+]*\)+)/g)[0];
	$scope.panelId = $scope.tabData.node.type;
	$scope.dateObject = {
		date: "",
		time: ""
	};

	$scope.getMediaTypeKeys = function(property) {
		var key, mediaKeys = [];
		for (key in scope.tabData.mediaAttributes[property]) {
			mediaKeys.push(key);
		}
		return mediaKeys;
	};

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

	$scope.getTimeStamp = function(){
		if($scope.isValidDate()){
			var time = $scope.dateObject.time.split('.');
			time[0] = parseInt(time[0]);
			time[1] = parseInt(time[1]);
			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.complete = function () {
		action = 'Complete ';
		var i,
		jsonService = {};
		$scope.createFeedback = null;
		for (var attr in $scope.usedProperties) {
			jsonService[attr] = $scope.usedProperties[attr];
		}
		var timestamp = $scope.getTimeStamp();
		if(angular.isDefined(timestamp)){
			jsonService["timestamp"] = timestamp;
		}
		
		//customcomplete current doesnt not get displayed as of Feb 8th, 2016
		if ($scope.customKey.length > 0) {
			jsonService["customcomplete"] = {}; 
		}

		for (i = 0; i < $scope.customKey.length; i++){
			if ($scope.customKey[i] && $scope.customKeyValues[i]){
				jsonService["customcomplete"][$scope.customKey[i]] = $scope.customKeyValues[i];
			}
		}

		if ($scope.tabData.node.type === 'Service'){
			action += ('Service: ' + $scope.tabData.node.service_id);
			csApi.completeService($scope.baseUrl, $scope.tabData.node.service_id, jsonService).then(successCallback, errorHandler);
		} else if ($scope.tabData.node.type === 'State'){
			action += ('State: ' + $scope.tabData.node.state_id);
			csApi.completeState($scope.baseUrl, $scope.tabData.node.service_id, $scope.tabData.node.state_id, jsonService).then(successCallback, errorHandler);
		} else if ($scope.tabData.node.type === 'Task'){
			action += ('Task: ' + $scope.tabData.node.task_id);
			csApi.completeTask($scope.baseUrl, $scope.tabData.node.service_id, $scope.tabData.node.task_id, jsonService).then(successCallback, errorHandler);
		}
	};
	
	$scope.$watch('usedProperties["disposition"]', function(newVal, oldVal) {
		var newDesc = $scope.tabData.dispositionDescriptions[$scope.panelId][newVal];
		if (newDesc === undefined)
			return;
		$scope.usedProperties["disposition_desc"] = $scope.tabData.dispositionDescriptions[$scope.panelId][newVal];
    });

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

	function successCallback (httpResponse) {
		$scope.addHttpRequestHistory(httpResponse, action);
		toaster.pop('success', $scope.tabData.node.type + ' successfully completed');

		if ($scope.tabData.oldCustomerId && $scope.tabData.oldQueryType){
			$scope.queryType = $scope.tabData.oldQueryType;
			$scope.customerId = $scope.tabData.oldCustomerId;
			$scope.tabData.queryById();
		}
		$scope.$apply();
	}
}]);