var objectStoreInspectorControllers = angular.module('objectStoresControllers', ['LocalStorageModule']);

function common_init($scope, $http, $sce, $location) {
    initSpinner();
    $scope.showError = function (error) {
        show_notification("error", error);
    }
    $scope.showNotification = function (message) {
        show_notification("info", message);
    }
    $scope.showSpinner = function () {
        showSpinner();
    }
    $scope.hideSpinner = function () {
        hideSpinner();
    }
    $scope.to_trusted = function (html) {
        return $sce.trustAsHtml(html);
    }
    $scope.go = function (path) {
        $location.path(path);
    }
    $scope.encodeValue = function (val) {
        return val;
    }
}

function ngGridFlexibleHeightPlugin(opts) {
    var self = this;
    self.grid = null;
    self.scope = null;
    self.init = function (scope, grid, services) {
        self.domUtilityService = services.DomUtilityService;
        self.grid = grid;
        self.scope = scope;
        var recalcHeightForData = function () {
            setTimeout(innerRecalcForData, 1);
        };
        var innerRecalcForData = function () {
            var gridId = self.grid.gridId;
            var footerPanelSel = '.' + gridId + ' .ngFooterPanel';
            var extraHeight = self.grid.$topPanel.height() + $(footerPanelSel).height();
            var naturalHeight = self.grid.$canvas.height() + 1;
            if (opts != null) {
                if (opts.minHeight != null && (naturalHeight + extraHeight) < opts.minHeight) {
                    naturalHeight = opts.minHeight - extraHeight - 2;
                }
                if (opts.maxHeight != null && (naturalHeight + extraHeight) > opts.maxHeight) {
                    naturalHeight = opts.maxHeight;
                }
            }

            var newViewportHeight = naturalHeight + 3;
            if (!self.scope.baseViewportHeight || self.scope.baseViewportHeight !== newViewportHeight) {
                self.grid.$viewport.css('height', newViewportHeight + 'px');
                self.grid.$root.css('height', (newViewportHeight + extraHeight) + 'px');
                self.scope.baseViewportHeight = newViewportHeight;
                self.domUtilityService.RebuildGrid(self.scope, self.grid);
            }
        };
        self.scope.catHashKeys = function () {
            var hash = '',
                idx;
            for (idx in self.scope.renderedRows) {
                hash += self.scope.renderedRows[idx].$$hashKey;
            }
            return hash;
        };
        self.scope.$watch('catHashKeys()', innerRecalcForData);
        self.scope.$watch(self.grid.config.data, recalcHeightForData);
    };
}

window.onresize = function () {


    var elem = document.getElementById('gridObjectstores');
    var height = 0;
    var body = window.document.body;
    if (window.innerHeight) {
        height = window.innerHeight;
    } else if (body.parentElement.clientHeight) {
        height = body.parentElement.clientHeight;
    } else if (body && body.clientHeight) {
        height = body.clientHeight;
    }
    elem.style.height = ((height - elem.offsetTop - 280) + "px");

};

function hasOwnProperty(obj, prop) {
    var proto = obj.__proto__ || obj.constructor.prototype;
    return (prop in obj) &&
        (!(prop in proto) || proto[prop] !== obj[prop]);
}

objectStoreInspectorControllers.directive('compileTemplate', function ($compile, $parse) {
    return {
        link: function (scope, element, attr) {
            var parsed = $parse(attr.ngBindHtml);

            function getStringValue() {
                return (parsed(scope) || '').toString();
            }

            //Recompile if the template changes
            scope.$watch(getStringValue, function () {
                $compile(element, null, -9999)(scope);  //The -9999 makes it skip directives so that we do not recompile ourselves
            });
        }
    }
});

objectStoreInspectorControllers.controller('inspectObjectStoreController', [
    '$scope', '$http', '$sce', '$location', '$routeParams',
    function ($scope, $http, $sce, $location, $routeParams) {
        common_init($scope, $http, $sce, $location);

        $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
        $scope.id = $routeParams.id;


        $scope.getRecordById = function () {
            console.log("Funcion getRecordById called");
        }



        $scope.start = $routeParams['start'];
        if ($scope.start == null)
            $scope.start = 0;
        else
            $scope.start = parseInt($scope.start);


        $scope.record_id = $routeParams['query'];




        $scope.previousPage = 0

        $scope.nextPage = 0

        $scope.loadInfo = function () {

            $http.post('objectStore/getObjectStoreInfo.do', $.param({
                'objId': $routeParams.id,
                'from': $scope.start,
                'id': $scope.record_id
            })).success(function (data) {

                $scope.objectStoreInfo = data;
                if (hasOwnProperty($scope, 'results') == false) {
                    $scope.searchResult = {}
                }

                $scope.searchResult.total = data.size;

                $scope.previousPage = Math.max($scope.start - 25, 0);
                $scope.nextPage = Math.min($scope.searchResult.total, $scope.start + 25);
            }).error(function () {
                $scope.showError('Error getting info from objectStore');

            });

        };

        $scope.loadInfo();


    }]);

objectStoreInspectorControllers.controller('objectStoresController', [
    '$scope', '$http', '$sce', '$location',

    function ($scope, $http, $sce, $location) {
        common_init($scope, $http, $sce, $location);
        $scope.showSpinner();
        $http.get('objectStore/listObjectStores.do').success(function (data) {
            $scope.hideSpinner();
            $scope.objTable = data;
        }).error(function () {
            $scope.showError('Error listing xmldb collections');
            $scope.hideSpinner();
        });

        $scope.refreshInfo = function () {
            console.log("Should reload Info")
        }

        $scope.gridOptions = {
            data: 'objTable',
            enableRowSelection: false,
            enableCellEditOnFocus: false,
            enableHighlighting: true,
            plugins: [new ngGridFlexibleHeightPlugin()],

            columnDefs: [
                {
                    field: 'objectStoreId',
                    displayName: 'ID',
                    cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><b>{{row.getProperty(col.field)}}</b></div>',
                    headerClass: 'text-center',
                    width: '500px'
                },
                {field: 'interpretation', displayName: 'Interpretation'},
                {field: 'size', displayName: 'Size'},
                {
                    field: 'serviceURI',
                    displayName: 'Service URI',
                    cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><b ng-show="row.getProperty(col.field)"> {{row.getProperty(col.field)}} </b><b ng-hide="row.getProperty(col.field)" style="color: red"> Profile Missing! </b> </div>',
                    headerClass: 'text-center'
                },
                {
                    field: 'objectStoreId',
                    displayName: 'View',
                    cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><b style="color:red" ng-show=\'row.getProperty("missingObjectStore")\'>Missing ObjectStore</b> <a ng-hide=\'row.getProperty("missingObjectStore")\'  href="objectstoreInspector.do#/inspect.do/{{row.getProperty(col.field)}}" class="btn btn-primary btn-xs" data-placement="top" title="{{row.getProperty(col.field)}}"><span class="glyphicon glyphicon-zoom-in"></span> inspect</a></div>',
                    width: '130px',
                    headerClass: 'text-center'
                }
            ]
        };


    }]);
