'use strict';
var healthDiagnosticController = BaseController.extend({
    /**
     * Initialize  Controller
     * @param $scope, current controller scope
     */

    init: function($scope, $q, $location, $cookies, $routeParams, reportService, wizardSharedService, commonHelper, notificationService, paginationService, modalWindowService, healthDiagnosticsService) {
        var self = this;

        this._super($scope);

        this.$location            = $location;
        this.$q                   = $q;
        this.$cookies             = $cookies;
        this._reportService       = reportService;
        this._wizardSharedService = wizardSharedService;
        this._commonHelper        = commonHelper;
        this._notificationService = notificationService;
        this.healthDiagnosticsService = healthDiagnosticsService;

        this.$scope.paginator     = paginationService;

        this.$scope.modalWindow   = modalWindowService;


        self.$scope.hostcontexts       = {};
        self.$scope.hostselectionstate = {};
        self.$scope.showEnvironmentFilterButtons = true;
        self.$scope.showDismissHostButton = false;

        self.$scope.savedSearchName = {};
        self.$scope.savedSearchCategory = {};
        self.$scope.is_public = {};

        // scope variables
        self.$scope.notification = {};

        self._initVIEWParams();

        self.$scope.Math = Math;

        self.$scope.reportId    = '';
        self.$scope.reportLabel = '';
        self.$scope.show_buttons = 0;

        self.$scope.reportRoles = {};

        self.$scope.roles    = this._commonHelper.getRolesArray();
        self.$scope.is_admin = self._commonHelper.checkifAdmin(self.$scope.roles);

        self.$scope.reportCategories = ReportCategories;

        self.$scope.SQL = {};

        self.$scope.externalSQL = '';
        self.$scope.reportType = '';

    },

    defineScope: function() {
        var self = this;

        self.$scope.instance    = "healthDiagnosticController";
        self.$scope.deleteTableView = 1;
        self.$scope.checkAllDeleteHost = false;
        self.$scope.selectedHostsList = {};
        self.$scope.selectedDismissList = {};
        self.$scope.deleteHostKeyMessage = {};
        self.$scope.sortReorder = self.sortReorder.bind(this);
        this.$scope.isObjEmpty      = this.checkIfObjEmpty.bind(this);
        this.$scope.runQuery = this.runQuery.bind(this);
        this.$scope.checkAllDeleteHost = this.checkAllDeleteHost.bind(this);
        this.$scope.deleteSeletedHosts = this.deleteSeletedHosts.bind(this);
        this.$scope.deleteConfirmedHosts = this.deleteConfirmedHosts.bind(this);
        this.$scope.closeHostDeleteConfirmDialog = this.closeHostDeleteConfirmDialog.bind(this);
        this.$scope.checkAllDismissHost = this.checkAllDismissHost.bind(this);
        this.$scope.dismissSelectedHosts = this.dismissSelectedHosts.bind(this);
        this.$scope.removeFromDismissed = this.removeFromDismissed.bind(this);
        this.$scope.deletePermanently = this.deletePermanently.bind(this);
        this.$scope.restoreDeletedHosts = this.restoreDeletedHosts.bind(this);

    },
   defineListeners: function() {
        var self = this;
       self.$scope.$on('healthReportSqlChanged', function (event, data) {
           self.$scope.reportType = data.type;
           self.$scope.externalSQL = data.sql;
           self.healthDiagnosticsService.getDismissedHosts(self.$scope.reportType).then(function (result) {
               self.$scope.dismissedHosts = result.data.data[0];
               angular.forEach(self.$scope.dismissedHosts.rows, function(value, index){
                   let key = value[0];
                   self.$scope.selectedDismissList[key] = {checked: false};
               });
           });
           if (self.$scope.externalSQL !== '') {
               self.$scope.SQL.SQLSTRING = self.$scope.externalSQL;
               self._wizardSharedService.scopeStateChanged(self.$scope.SQL);
               self._runQuery();
               self.$scope.show_buttons = 1;
               self.$scope.isChanges = 0;
               self.$scope.is_own = 1;
               self.$scope.can_edit = 0;
               self.$scope.can_subscribe = 0;
               self.$scope.is_subscribed = 0;
               self.$scope.is_public.input = 0;
               self._wizardSharedService.reportPropertiesChanged(self._commonHelper.getReportData(self.$scope));
           }
       })

        self.$scope.$on('paginatorChange', function() {
            self._runQuery('paging');
        });

        self.$scope.$on('subscribeToReport', function(event, data) {
          self.cleanStoredScope();
          self._reloadReport(data['id']);
        });

        self.$scope.$on('unSubscribeFromReport', function(event, data) {
          self.cleanStoredScope();
          self._reloadReport(data['id']);
        });
    },

   sortReorder: function(col,e) {
        var self = this;
        angular.forEach(self.$scope.VIEW.tablehead, function(el) {
            if (el.nameToSort===col)
            {
                el.sort = el.sort>0?-1:1;

                self.$scope.VIEW.sortColumn     = el.name;
                self.$scope.VIEW.sortDescending = el.sort>0 ? 0:1; //
            }
            else
            {
                el.sort = null;
            }
        });

        if (self.$scope.VIEW.sortColumn !== undefined && self.$scope.VIEW.sortColumn !=='')
        {
            self._runQuery('reorder');
        }
    },


    checkAllDeleteHost: function() {
        var self = this;
        self.$scope.selectedAllDeleteHost = !self.$scope.selectedAllDeleteHost;
        angular.forEach(self.$scope.selectedHostsList, function(value, key){
            self.$scope.selectedHostsList[key].checked = self.$scope.selectedAllDeleteHost;
        });
    },

    checkAllDismissHost: function() {
        var self = this;
        self.$scope.selectedAllDismissHost = !self.$scope.selectedAllDismissHost;
        angular.forEach(self.$scope.selectedDismissList, function(value, key){
            self.$scope.selectedDismissList[key].checked = self.$scope.selectedAllDismissHost;
        });
    },

    dismissSelectedHosts: function() {
        var self = this;
        self.$scope.selectedKeysForDismiss = [];
        angular.forEach(self.$scope.selectedHostsList, function(value, key){
            if (value.checked === true)
            {
                self.$scope.selectedKeysForDismiss.push(key);
            }
        });

        if (self.$scope.selectedKeysForDismiss.length) {
            self.healthDiagnosticsService.dismissHosts(self.$scope.selectedKeysForDismiss, self.$scope.reportType).then(function () { window.location.reload(); });
        }
    },

    removeFromDismissed: function() {
        var self = this;
        self.$scope.selectedKeys = [];
        angular.forEach(self.$scope.selectedDismissList, function(value, key){
            if (value.checked === true)
            {
                self.$scope.selectedKeys.push(key);
            }
        });

        if (self.$scope.selectedKeys.length) {
            self.healthDiagnosticsService.removeFromDismissed(self.$scope.selectedKeys, self.$scope.reportType).then(function () { window.location.reload(); });
        }
    },

    deleteSeletedHosts: function() {
        var self = this;
        self.$scope.selectedKeysForDelete = [];
        angular.forEach(self.$scope.selectedHostsList, function(value, key){
            if (value.checked === true)
            {
                self.$scope.selectedKeysForDelete.push(key);
            }
        });
        if ( self.$scope.selectedKeysForDelete.length)
        {
           self.$scope.showDeleteButton = true;
            self.$scope.modalWindow.open('deleteHostConfirmModal', self.$scope);
        }
    },
    
    _checkedHosts: function () {
        return Object.keys(this.$scope.selectedHostsList).filter(key => this.$scope.selectedHostsList[key].checked)
    },
    
    deletePermanently: function() {
        const tasks = this._checkedHosts()
            .reduce((acc, key) => {
                acc.push(this.healthDiagnosticsService.deletePermanently(key))
                return acc;
            }, []);
        
        Promise.all(tasks)
            .then(() => window.location.reload())
            .catch(error => notify.error(error.data));
    },

    restoreDeletedHosts: function() {
       const tasks = this._checkedHosts()
            .reduce((acc, key) => {
                acc.push(this.healthDiagnosticsService.restoreDeletedHost(key))
                return acc;
            }, []);
       
       Promise.all(tasks)
           .then(() => window.location.reload())
           .catch(error => notify.error(error.data));
    },

    deleteConfirmedHosts: function() {
        var self = this;
        self.$scope.showDeleteButton = false;
        var successCallback = function(data) {
           self.$scope.rerunQueryAfterDelete = true;
           self.$scope.selectedHostsList = {};
           self.$scope.deleteHostKeyMessage.type = 'alert-success';
           self.$scope.deleteHostKeyMessage.message = 'Host deleted successfully';
        };
        var failureCallback = function(error) {
           self.$scope.rerunQueryAfterDelete = false;
           self.$scope.deleteHostKeyMessage.type = 'alert-error';
           self.$scope.deleteHostKeyMessage.message = 'Failed deleting hosts. Error: '+ error.data;
        };
        self._reportService.deleteHosts(self.$scope.selectedKeysForDelete).then(successCallback,failureCallback);
    },

    closeHostDeleteConfirmDialog: function() {
        var self = this;
        self.$scope.deleteHostKeyMessage = {};
        self.$scope.modalWindow.close('deleteHostConfirmModal');
        if (self.$scope.rerunQueryAfterDelete)
        {
            self.runQuery();
        }
    },

    _runQuery: function(action) {
        var self = this;

        self._notificationService.resetNotification();
        if (self.$scope.externalSQL === '')
        {
            // apply current envirnment to SQL
            self.$scope.SQL.hostcontexts = self.$scope.hostcontexts;
        }

        // reset pagination to default if this is new query
        if (action !== 'reorder' && action !== 'paging' && action !== 'environmentFilter')
        {
           self.$scope.paginator.paginationReset();
        }

        var data = $.param({
            SQLString      : self.$scope.SQL.SQLSTRING.length > 0 ? encodeURIComponent(self.$scope.SQL.SQLSTRING) : false,
            sortColumn     : self.$scope.VIEW.sortColumn,
            sortDescending : self.$scope.VIEW.sortDescending,

            skip           : self.$scope.paginator.skip,
            limit          : self.$scope.paginator.rowsPerPage,
            apiUrl         : '/health-diagnostic/report/' + self.$scope.reportType
        });


        self._reportService.runQuery(data).then(
        function(result)
        {
            common.globalSpinner.show();
            self.$scope.result = result.data;
            self.$scope.showdDeleteHostButton = false;
            self.$scope.showDismissHostButton = true;
            if (self.$scope.deleteTableView && result.data.rows.length) {
               self.$scope.showdDeleteHostButton = true;
               angular.forEach(result.data.rows, function(value, key){
                    var key = value[0];
                    self.$scope.selectedHostsList[key] = {};
                    self.$scope.selectedHostsList[key].checked = false;
                });
            }
            // do not reset table header and sorting params if result table column headers are the same
            if (action !== 'reorder' && action !== 'paging' && action !== 'environmentFilter')
            {
                self._initVIEWParams();

                angular.forEach(self.$scope.result.header, function(field, key){
                    var tmp   = {};
                    tmp.name  = field.columnName;
                    tmp.type = field.columnType;

                    tmp.sort = 0;
                    tmp.fieldIndex = key;
                    tmp.nameToSort = tmp.name + '_' + key;
                    self.$scope.VIEW.tablehead.push(tmp);
                });
            }

            self.$scope.VIEW.rows = self.$scope.result.rows;
            self.$scope.VIEW.rowCount = self.$scope.result.rowCount;

            self.$scope.paginator.refreshPaginator(result.data.rowCount);

            if(self.$scope.result.rowCount === 0)
            {
                var error = self._notificationService.createObjectForNotification('warning', 505, 'Query returned 0 rows');
                self._notificationService.setNotification(error.type, error.data);
            }
            common.globalSpinner.hide();
        },
        function(error) {
            error.data[0].text = error.data[0].text || 'Error encountered.Please view the logs for more detailed information.';
            self._notificationService.setNotification('error', error.data);
            common.globalSpinner.hide();
        });
     },

     runQuery:function() {
        var self = this;
        self._runQuery();
     },
    _initVIEWParams: function(){
        var self = this;
        self.$scope.VIEW = {};

        self.$scope.VIEW.sortColumn     = '';
        self.$scope.VIEW.sortDescending = 0;

        self.$scope.VIEW.tablehead      = [];
    },


    checkIfObjEmpty: function (val)
    {
       var self = this;
       return self._commonHelper._isObjEmpty(val);
    }
});

healthDiagnosticController.$inject =
        [   '$scope',
            '$q',
            '$location',
            '$cookies',
            '$routeParams',
            'reportService',
            'wizardSharedService',
            'commonHelper',
            'notificationService',
            'paginationService',
            'modalWindowService',
            'healthDiagnosticsService'
        ];