'use strict';

app.directive('deleteVariable', function ($rootScope, $modal, $timeout) {
	return {
		restrict: 'A',
		scope: {
			system: '=',
			steps: '=',
			variable: '='
		},
		controller: function ($rootScope, $scope, $element, Systems, toastr) {
			var modal = $modal({scope: $scope, template: 'views/modal-tpls/delete-variable.html', show: false});
			
			$scope.delete = function () {
				var data = JSON.stringify({ id: $scope.variable.id});

				var roomId = null;
				if ($rootScope.virtualEditor) {
					roomId = Systems.getCurrentRoom();
				}

				Systems.deleteVariable(data, roomId).then(function (data) {
					console.log('data=', data);
          var variable = _.find($scope.system.variables || $scope.system.rooms[0].variables, {'id': $scope.variable.id});

					if(variable){
						///$scope.system.variables에서 삭제한 variable을 제거
            if ($rootScope.virtualEditor) {
              var idx = $scope.system.rooms[0].variables.indexOf(variable);
              $scope.system.rooms[0].variables.splice(idx, 1);
            } else {
              var idx = $scope.system.variables.indexOf(variable);
              $scope.system.variables.splice(idx, 1);
              console.log('variables=', $scope.system.variables);
            }

						///$scope.steps에 삭제한 variable을 참조하고 있다면 제거
						_.forEach($scope.steps, function (step) {
							if(step && (step.type == 4 || step.type == 5)){
								if(step.id == variable.id){
									idx = $scope.steps.indexOf(step);
									$scope.steps.splice(idx, 1);	
								}
							}
						});
					}

				}).catch(function(error) {
					toastr.error(error, 'Error');
				});

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

			$element.on('click', function(event) {
				event.preventDefault();
				modal.$promise.then(modal.show);
			});
		}
	};
});