/** * Created by robin on 11/4/15. */ angular.module('camotionAdmin') .controller('SensorEditController', ['$scope', 'SensorsService', 'data', 'dialogs', '$q', 'luticateAuthCache', 'HelperService', function($scope, SensorsService, data, dialogs, $q, luticateAuthCache, HelperService) { if (data != null) { $scope.sensor = data; $scope.sensor.Data = JSON.parse($scope.sensor.Data); $scope.sensor.sensor_id = $scope.sensor.Id; $scope.permission = "CAMOTION_SENSOR_EDIT"; } else { $scope.sensor = { Name: "", Description: "", Data: null, HostId: null, SensorTypeId: null }; $scope.permission = "CAMOTION_SENSOR_ADD"; } $scope.hosts = {}; $scope.sensorTypes = {}; var promiseLoadForeign = { id: "promiseLoadForeign", groups: ["modal"] }; HelperService.getForeignEntities(SensorsService, promiseLoadForeign).then(function(data) { $scope.hosts = data.hosts; $scope.sensorTypes = data.types; if ($scope.sensor.Id == null) { var keys = Object.keys($scope.hosts); if (keys.length != 0) { $scope.sensor.HostId = $scope.hosts[keys[0]].Id; }keys = Object.keys($scope.sensorTypes); if (keys.length != 0) { $scope.sensor.SensorTypeId = $scope.sensorTypes[keys[0]].Id; $scope.setSensorType($scope.sensorTypes[keys[0]]); } } else if ($scope.sensor.Data == null) { $scope.setSensorType($scope.sensorTypes[$scope.sensor.SensorTypeId]); } }); $scope.submitForm = function() { if (luticateAuthCache.hasEffectivePermission($scope.permission)) { $scope.sensor.Data = JSON.stringify($scope.sensor.Data); if ($scope.sensor.Id != null) { var promiseEditSensor = { id: "promiseEditSensor", loaderGroups: ["modal"] }; return SensorsService.edit($scope.sensor, promiseEditSensor); } else { var promiseAddSensor = { id: "promiseAddSensor", loaderGroups: ["modal"] }; return SensorsService.add($scope.sensor, promiseAddSensor); } } else { var defer = $q.defer(); defer.resolve(); return defer.promise; } }; $scope.setSensorType = function(sensorType) { $scope.sensor.SensorTypeId = sensorType.Id; $scope.sensor.Data = JSON.parse($scope.sensorTypes[$scope.sensor.SensorTypeId].DefaultData); }; }]);