'use strict';

app.directive('newVariable', function ($rootScope, $modal, $timeout) {
	return {
		restrict: 'A',
		scope: {
			system: '=',
			newVar: '='
		},
		controller: function ($rootScope, $scope, $element, Systems, toastr) {
			$scope.variableTypes = [{name:'True False', value:0}, {name:'String', value:1}, {name:'Integer', value:2}];

			$scope.title = '';

			var modal = $modal({scope: $scope, template: 'views/modal-tpls/new-variable.html', show: false});

			
			$scope.addVariable = function () {

				var variable = {type: $scope.newVar.type, name:$scope.newVar.name, value: $scope.newVar.value};
				var data  = JSON.stringify(variable);

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

				Systems.addVariable(data, roomId).then(function (data) {
					console.log('return variable id=', data);
					variable.id = data;
          if ($rootScope.virtualEditor) {
            $scope.system.rooms[0].variables.push(variable);
          } else {
            $scope.system.variables.push(variable);
          }

					console.log('$scope.system.variables=', $scope.system.variables);
				}).catch(function(error) {
					toastr.error(error, 'Error');
				});
				modal.$promise.then(modal.hide);
			}; 

			$element.on('click', function(event) {
				event.preventDefault();
				$scope.title = 'New Variable: ' + $scope.variableTypes[$scope.newVar.type].name;
				modal.$promise.then(modal.show);
			});
		}
	};
});