/*jslint node: true */
/*jslint browser: true*/
/*jslint nomen: true*/
/*global angular, BaseController, CFE_mapping, defaultSQL, alert, $, common*/

'use strict';

let fileIntegrityMonitoringController = BaseController.extend({

    init: function ($scope, $location, reportService, commonHelper, notificationService, wizardSharedService,
                    fileChangesSqlService, paginationService, $routeParams) {
        let self = this;
        this._super($scope);
        this._reportService = reportService;
        this._notificationService = notificationService;
        this.commonHelper = commonHelper;
        this.fileChangesSqlService = fileChangesSqlService;
        this.$routeParams = $routeParams;

        this.timeout = null;
        this.$scope.paginator = paginationService;
        this.$location = $location;

        this.$scope.typeFilter = {
            "contentChange": true,
            "diff": true,
            "fileRemoved": true,
            "fileAdded": true,
            "fileStats": true
        };
        this.$scope.fileFilter = null;
        this.wizardSharedService = wizardSharedService;

        self.$scope.alertData = {};
        self.$scope.hostcontexts = {};
        self.$scope.excludedHosts = '';
        self.$scope.showEnvironmentFilterButtons = true;

        self.$scope.SQL = {};
        self.$scope.SQL.filters = [];
        self.$scope.SQL.columns = [];

        self.$scope.is_admin = self.commonHelper.checkifAdmin(self.$scope.roles);

        self.$scope.is_own = 1;
        self.$scope.show_buttons = 1;

        self.initDateParams();
        self.initViewParams();
        self.initRouteParams();
        self.runQuery();
    },

    defineScope: function () {
        this.$scope.instance = "fileIntegrityMonitoringController";
        this.$scope.sortReorder = this.sortReorder.bind(this);
        this.$scope.scheduleReport = this.scheduleReport.bind(this);
        this.$scope.clearAll = this.clearAll.bind(this);
    },

    defineListeners: function () {
        let self = this;

        self.$scope.$on("runQuery_EVENT", function () {
            self.runQuery();
        });

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

        self.$scope.$on('clearFilters_EVENT', function () {
            self.$scope.$broadcast('clearAll_EVENT');
        });

        self.$scope.$watchCollection('typeFilter', function () {
            self.runQuery();
        });

        self.$scope.$watchCollection('filterDateRange', function () {
            self.runQuery();
        });

        self.$scope.$on('fileSelected', function (event, value) {
            self.$scope.fileFilter = value.id;
            self.runQuery();
        });

        self.$scope.$on("hostContextApply_Event", function (event, hostContextObj) {
            self.$scope.SQL.hostcontexts = angular.copy(hostContextObj.hostcontexts);
            self.$scope.SQL.hostcontextsprofileid = angular.copy(hostContextObj.hostcontextsprofileid);
            self.$scope.SQL.hostcontextspath = angular.copy(hostContextObj.hostcontextspath);
            self.$scope.hostcontexts = self.$scope.SQL.hostcontexts;
            self.$scope.alertData.hostContexts = self.$scope.SQL.hostcontexts;
            self.$scope.$broadcast('environmentFilter_EVENT');
        });

        self.$scope.$on('environmentExcludeChanged_Event', function (event, excludedHosts) {
            if (Object.keys(excludedHosts).length) {
                self.$scope.SQL.excludedHosts = {
                    name: Object.values(excludedHosts).join(', '),
                    excludes: Object.keys(excludedHosts)
                };
                self.$scope.excludedHosts = {
                    name: Object.values(excludedHosts).join(', '),
                    excludes: Object.keys(excludedHosts)
                };
                self.$scope.alertData.excludedHosts = {
                    name: Object.values(excludedHosts).join(', '),
                    excludes: Object.keys(excludedHosts)
                };
            } else {
                self.$scope.excludedHosts = '';
                self.$scope.SQL.excludedHosts = '';
                self.$scope.alertData.excludedHosts = '';
            }
        });
    },
    clearAll: function () {
        this.initViewParams();
        this.$scope.currentChart = {};
        this.$scope.$broadcast('clearAll_EVENT');
        this.$scope.$broadcast('runDefaultReport_EVENT', this.$scope.selectDefaultColumns);
    },
    scheduleReport: function () {
        this.wizardSharedService.scopeStateChanged(this.$scope.SQL);
        this.wizardSharedService.reportPropertiesChanged(this.commonHelper.getReportData(this.$scope));
        this.$location.path('/report/schedule');
    },

    runQuery: function (action) {
        let self = this;
        if (this.timeout == null) {
            this.timeout = setTimeout(function () {
                self._runQuery(action)
                self.timeout = null;
            }, 200);
        }
    },

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

        self._notificationService.resetNotification();

        this.$scope.SQL.SQLSTRING = self.fileChangesSqlService.getSql(self.$scope.typeFilter, self.$scope.filterDateRange, self.$scope.fileFilter);
        // reset pagination to default if this is new query
        if (action !== 'reorder' && action !== 'paging' && action !== 'environmentFilter') {
            self.$scope.paginator.paginationReset();
        }

        let 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,

            includes: ((self.$scope.SQL.hostcontexts !== undefined && self.$scope.SQL.hostcontexts.includes !== undefined) ? self.$scope.SQL.hostcontexts.includes : []),
            excludes: ((self.$scope.SQL.excludedHosts !== undefined && self.$scope.SQL.excludedHosts.excludes !== undefined) ? self.$scope.SQL.excludedHosts.excludes : [])
        });

        self._reportService.runQuery(data).then(
            function (result) {
                common.globalSpinner.show();
                self.$scope.result = self.commonHelper.removeHostkeyFromResult(result.data);

                // 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) {
                    let 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();
            });
    },

    initViewParams: function () {
        this.$scope.VIEW = {};
        this.$scope.VIEW.sortColumn = '';
        this.$scope.VIEW.sortDescending = 0;
        this.$scope.VIEW.tablehead = [];
    },

    initRouteParams: function () {
        let self = this;

        if (this.$routeParams.changeType) {
            Object.keys(this.$scope.typeFilter).forEach(function (index) {
                self.$scope.typeFilter[index] = index === self.$routeParams.changeType ? true : false;
            })
        }
    },

    initDateParams: function () {
        this.$scope.todayDate = new Date();
        this.$scope.dateStart = this.commonHelper.returnDate(6, true);

        if (this.$routeParams.from && this.$routeParams.to) {
            this.$scope.dateStart = new Date(Number(this.$routeParams.from));
            this.$scope.todayDate = this.$scope.todayDate < new Date(Number(this.$routeParams.to)) ? this.$scope.todayDate : new Date(Number(this.$routeParams.to));
        }

        this.$scope.dateOpts = {
            ranges: {
                'Today': [this.$scope.todayDate, this.$scope.todayDate],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()]
            },
            applyClass: 'btn-primary',
            separator: ' to ',
            buttonClasses: ['pull-right', 'btn']
        };

        this.$scope.filterDateRange = {
            startDate: this.$scope.dateStart,
            endDate: this.$scope.todayDate,
            dateLimit: {days: 1},
            maxDate: this.$scope.todayDate
        };
    },

    sortReorder: function (col, e) {
        let 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');
        }
    }
});


fileIntegrityMonitoringController.$inject = ['$scope',
    '$location',
    'reportService',
    'commonHelper',
    'notificationService',
    'wizardSharedService',
    'fileChangesSqlService',
    'paginationService',
    '$routeParams'
];
