var mdstoreInspectorControllers = angular.module('mdstoreInspectorControllers', ['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);
    };
}

mdstoreInspectorControllers.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
            });
        }
    }
});

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


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

        $scope.mdId = $routeParams.id;
        $scope.from_page = 0;
        $scope.to_page = 0;
        $scope.queryValues = {}



        $scope.loadInfo = function () {
            $scope.showSpinner();
            $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
            $http.post('mdstore/getMdStoreInfo.do', $.param({
                'id': $routeParams.id
            })).success(function (data) {
                $scope.hideSpinner();
                $scope.mdStoreInfo = data;
                if (hasOwnProperty($scope, 'searchResult') == false) {
                    $scope.searchResult = {}
                }
                $scope.queryValues = {"body": "", "id": ""};

                $scope.searchResult.total = data.size;
            }).error(function () {
                $scope.showError('Error getting info from mdstore');
                $scope.hideSpinner();
            });
            $scope.hideSpinner();
        }

        $scope.findIndexFields = function (indexField) {
            $scope.showSpinner();
            if ($scope.query == null) {
                if ($scope.searchResult != null)
                    $scope.searchResult.total = $scope.mdStoreInfo.size
            }
            $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
            $http.post('mdstore/findByIndexField', $.param({
                'mdId': $routeParams.id, 'from': $scope.from_page, 'query': $scope.query,
                'indexField': indexField
            })).success(function (data) {
                $scope.hideSpinner();
                $scope.searchResult.records = data;
                $scope.to_page = Math.min($scope.from_page + 10, $scope.searchResult.total);
            }).error(function () {
                $scope.showError('Error getting info from mdstore');
                $scope.hideSpinner();
            });

        }

        $scope.getResults = function () {
            $scope.showSpinner();
            $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
            if ($scope.query == null) {
                if ($scope.searchResult != null)
                    $scope.searchResult.total = $scope.mdStoreInfo.size
            }
            $http.post('mdstore/mdStoreResults', $.param({
                'mdId': $routeParams.id, 'from': $scope.from_page
            })).success(function (data) {
                $scope.hideSpinner();
                $scope.searchResult.records = data.result;
                $scope.searchResult.total = data.count;
                $scope.to_page = Math.min($scope.from_page + 10, $scope.searchResult.total);
            }).error(function () {
                $scope.showError('Error getting info from mdstore');
                $scope.hideSpinner();
            });
        };


        $scope.startSearch = function () {
            $scope.from_page = 0;
            return $scope.searchByQuery()
        }

        $scope.searchByQuery = function () {
            $scope.showSpinner();
            if ($scope.query == null) {
                if ($scope.searchResult != null)
                    $scope.searchResult.total = $scope.mdStoreInfo.size
            }
            var query = {};
            var setValue;
            for (var key in $scope.queryValues) {
                if ($scope.queryValues[key].length > 0) {
                    query[key] = $scope.queryValues[key];
                    setValue = true;
                }
            }
            if (setValue == false)
                return $scope.getResults();
            query["mdId"] = $routeParams.id;
            query["page"] = $scope.from_page;
            $http.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
            $http.post('mdstore/findRecords', query)
                .success(function (data) {
                    $scope.hideSpinner();
                    $scope.searchResult.records = data.result;
                    $scope.searchResult.total = data.count;
                    $scope.to_page = Math.min($scope.from_page + 10, $scope.searchResult.total);
                }).error(function () {
                $scope.showError('Error getting info from mdstore');
                $scope.hideSpinner();
            });
        };

        $scope.getRecordById = function () {

            if (($scope.record_id != null) && ($scope.record_id.length > 0)) {
                $scope.showSpinner();
            }

            $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
            $http.post('mdstore/mdStoreResults', $.param({
                'mdId': $routeParams.id, 'from': $scope.from_page, 'id_query': $scope.record_id
            })).success(function (data) {
                $scope.hideSpinner();
                $scope.searchResult.records = data.records.result;
                $scope.searchResult.total = data.records.total;
                $scope.to_page = 0
                if (data == null) {
                    $scope.to_page = 0
                    $scope.searchResult.total = 0
                }
                else {
                    $scope.to_page = data.length
                    $scope.searchResult.total = data.length
                }

            }).error(function () {
                $scope.showError('Error getting info from mdstore');
                $scope.hideSpinner();
            });
        };

        $scope.nextPage = function () {
            if ($scope.from_page < $scope.searchResult.total - 10) {
                $scope.from_page = $scope.from_page + 10;
                $scope.searchByQuery();
                $scope.to_page = Math.min($scope.from_page + 10, $scope.searchResult.total);
            }

        };

        $scope.prevPage = function () {
            if ($scope.from_page + 10 > 10) {
                $scope.from_page = $scope.from_page - 10;
                $scope.searchByQuery();
                $scope.to_page = Math.min($scope.from_page + 10, $scope.searchResult.total);
            }

        }

        $scope.loadInfo();

        $scope.getResults();
    }]);


mdstoreInspectorControllers.controller('mdstoresController', [
    '$scope', '$http', '$sce', '$location',
    function ($scope, $http, $sce, $location) {
        common_init($scope, $http, $sce, $location);
        $scope.showSpinner();
        $http.get('mdstore/listMDStores.do').success(function (data) {
            $scope.hideSpinner();
            $scope.mdTable = data;
        }).error(function () {
            $scope.showError('Error listing xmldb collections');
            $scope.hideSpinner();
        });

        $scope.refreshInfo = function () {

            $scope.showSpinner();
            $http.get('mdstore/reloadInfo').success(function (data) {
                $scope.hideSpinner();
                $scope.mdTable = data;
            }).error(function () {
                $scope.showError('Error listing xmldb collections');
                $scope.hideSpinner();
            });

        }

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

            columnDefs: [
                {field: 'format', displayName: 'Format', width: '55px'},
                {field: 'layout', displayName: 'Layout', width: '55px'},
                {field: 'interpretation', displayName: 'Interpretation', width: '100px'},
                {field: 'lastStorageDate', displayName: 'Last Storage', width: '120px'},
                {field: 'size', displayName: 'Size', width: '90px'},
                {field: 'serviceURI', displayName: 'Service URI', width: '350px'},
                {
                    field: 'id',
                    displayName: 'profile',
                    cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><a href="isManager.do#/profile/{{row.getProperty(col.field)}}" class="btn btn-primary btn-xs" data-placement="top" ><span class="glyphicon glyphicon-zoom-in"></span> profile</button></div>',
                    width: '80px',
                    headerClass: 'text-center'
                },
                {
                    field: 'id',
                    displayName: 'View',
                    cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><a href="mdstoreInspector.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</button></div>',
                    width: '80px',
                    headerClass: 'text-center'
                },
                {
                    field: 'datasourcesInvolved',
                    displayName: 'Datasource',
                    cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><b>{{row.getProperty(col.field).datasourceName}}</b> </div>',
                    headerClass: 'text-center'
                }

            ]
        };

    }]);

window.onresize = function () {

    var elem = document.getElementById('gridMdstores');
    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");

};


