angular.module('camotionAdmin')
    .controller('CamerasController', ['$scope', 'CamerasService', 'HelperService', '$q', 'luticateAuthCache',
        function($scope, CamerasService, HelperService, $q, luticateAuthCache) {

            $scope.foreighLoaded = false;
            $scope.hosts = {};
            $scope.cameraTypes = {};

            $scope.luTable = {
                columns: [
                    {
                        name: "Name",
                        width: 3,
                        getValue: function (item) {
                            return item.Name;
                        }
                    },
                    {
                        name: "Type",
                        width: 3,
                        getValue: function (item) {
                            return $scope.cameraTypes[item.CameraTypeId].Name;
                        }
                    }, {
                        name: "Description",
                        width: 6,
                        getValue: function (item) {
                            return item.Description;
                        }
                    }
                ],

                canAdd: function()
                {
                    return luticateAuthCache.hasAllEffectivePermissions([
                        'CAMOTION_CAMERA_ADD',
                        'CAMOTION_HOST_GET'
                    ])
                },

                canDel: 'CAMOTION_CAMERA_DEL',

                canEdit: function()
                {
                    return true;
                },

                getLoadPagePromise: function (page, perPage, query, promise) {
                    var defer = $q.defer();
                    CamerasService.getAll({page: page, perPage: perPage, query: query}, promise)
                        .then(function(cameras)
                        {
                            if (!$scope.foreighLoaded) {
                                HelperService.getForeignEntities(CamerasService, promise).then(function (data) {
                                    $scope.hosts = data.hosts;
                                    $scope.cameraTypes = data.types;
                                    $scope.foreighLoaded = true;
                                    defer.resolve(cameras);
                                }, defer.reject);
                            }
                            else {
                                defer.resolve(cameras);
                            }
                        }, defer.reject);
                    return defer.promise;
                },

                getDelPromise: function (id, promise) {
                    return CamerasService.del({camera_id: id}, promise);
                },

                getEditController: function () {
                    return "CameraEdit";
                }
            };
    }]);