/** * Created by robin on 11/4/15. */ angular.module('camotionAdmin') .controller('CommandEditController', ['$scope', 'CommandsService', 'data', 'dialogs', '$q', 'luticateAuthCache', 'HelperService', function($scope, CommandsService, data, dialogs, $q, luticateAuthCache, HelperService) { if (data != null) { $scope.command = data; $scope.command.Data = JSON.parse($scope.command.Data); $scope.command.command_id = $scope.command.Id; $scope.permission = "CAMOTION_COMMAND_EDIT"; } else { $scope.command = { Name: "", Description: "", Data: null, HostId: null, CommandTypeId: null }; $scope.permission = "CAMOTION_COMMAND_ADD"; } $scope.hosts = {}; $scope.commandTypes = {}; var promiseLoadForeign = { id: "promiseLoadForeign", groups: ["modal"] }; HelperService.getForeignEntities(CommandsService, promiseLoadForeign).then(function(data) { $scope.hosts = data.hosts; $scope.commandTypes = data.types; if ($scope.command.Id == null) { var keys = Object.keys($scope.hosts); if (keys.length != 0) { $scope.command.HostId = $scope.hosts[keys[0]].Id; }keys = Object.keys($scope.commandTypes); if (keys.length != 0) { $scope.command.CommandTypeId = $scope.commandTypes[keys[0]].Id; $scope.setCommandType($scope.commandTypes[keys[0]]); } } else if ($scope.command.Data == null) { $scope.setCommandType($scope.commandTypes[$scope.command.CommandTypeId]); } }); $scope.submitForm = function() { if ($scope.command.Data == null) { $scope.command.Data = {}; } if (luticateAuthCache.hasEffectivePermission($scope.permission)) { $scope.command.Data = JSON.stringify($scope.command.Data); if ($scope.command.Id != null) { var promiseEditCommand = { id: "promiseEditCommand", loaderGroups: ["modal"] }; return CommandsService.edit($scope.command, promiseEditCommand); } else { var promiseAddCommand = { id: "promiseAddCommand", loaderGroups: ["modal"] }; return CommandsService.add($scope.command, promiseAddCommand); } } else { var defer = $q.defer(); defer.resolve(); return defer.promise; } }; $scope.setCommandType = function(commandType) { $scope.command.CommandTypeId = commandType.Id; $scope.command.Data = JSON.parse($scope.commandTypes[$scope.command.CommandTypeId].DefaultData); }; }]);