'use strict';

app.directive('addSpecialFunction', function () {
	return {
		restrict: 'A',
		scope: {
			steps: '=',
			sfunc: '='
		},
		controller: function($scope, $element, $modal, toastr) {
			$scope.specialFuncTypes = [{title:'Set Variable: ', value:0}, {title:'If Else: ', value:1}];
			$scope.variableTypes = [{name:'True False', value:0}, {name:'String', value:1}, {name:'Integer', value:2}];
			$scope.opIntTypes = ['=', '>=', '<'];
			$scope.opStrTypes = ['include', '='];
			$scope.sfunc.cond = {type:1};
			$scope.title = '';

			
			var modal;
			if(0 == $scope.sfunc.type)
			{
				modal = $modal({ scope: $scope, placement: 'top', template:'views/modal-tpls/add-variable-function.html', show:false});
			}
			else
			{
				modal = $modal({ scope: $scope, placement: 'top', template:'views/modal-tpls/add-if-function.html', show:false});
			}

			$scope.addStep = function() {

				modal.$promise.then(modal.hide);

				$scope.sfunc.value += '';

				var step = null;

				if(0 == $scope.sfunc.type)///set variable action
				{
					var dispValue = $scope.sfunc.value;
					if($scope.sfunc.variable.type == 0){
						if($scope.sfunc.value == 0){
							dispValue = 'false' ;
						}
						else if($scope.sfunc.value == 1){
							dispValue = 'true' ;
						}
						else if($scope.sfunc.value == 2){
							dispValue = 'invert' ;
						}
					}

					step = {'name': 'VAR ' + $scope.sfunc.variable.name + '= ' + dispValue, 'type': 5, 'id': $scope.sfunc.variable.id, 'value': $scope.sfunc.value };
					$scope.steps.push(step);
				}
				else///if/else action
				{
					$scope.sfunc.cond.id = $scope.sfunc.variable.id;
					$scope.sfunc.cond.value +=  '';
					var name = '';
					if($scope.sfunc.variable.type == 0){
						name = 'If: ' + $scope.sfunc.variable.name + ', ' + ($scope.sfunc.cond.value == 1 ? 'True':'False');
					} else{
						name = 'If: ' + $scope.sfunc.variable.name + ' ' +  $scope.sfunc.cond.operate + ' ' + $scope.sfunc.cond.value;
					} 

					step = {'name': name, 'type': 4, 'cond': $scope.sfunc.cond, 'true': [], 'false': []};

					step.steps = [{name:'True', steps:[]}, {name:'False', steps:[]}];

					$scope.steps.push(step);
				}
				
			};

			$element.on('click', function(event) {
				event.preventDefault();
				$scope.title = $scope.specialFuncTypes[$scope.sfunc.type].title + $scope.variableTypes[$scope.sfunc.variable.type].name;
				$scope.title += ($scope.sfunc.type == 1 ? ' Variable' : '');

				if($scope.sfunc.variable.type == 1) {
					$scope.sfunc.cond.operate = $scope.opStrTypes[0];
				}	else if($scope.sfunc.variable.type == 2) {
					$scope.sfunc.value = parseInt($scope.sfunc.variable.value, 10);
					$scope.sfunc.cond.value = parseInt($scope.sfunc.variable.value, 10);
					$scope.sfunc.cond.operate = $scope.opIntTypes[0];
				}
				
				modal.$promise.then(modal.show);
			});

		}
	};
});
