'use strict';
/**
 * Show list of saved reports
 **/
var indexController = BaseController.extend({
    /**
     * Initialize  Controller
     * @param $scope, current controller scope
     */
    init: function($scope, $location, reportService, notificationService, wizardSharedService, paginationService, commonHelper, modalWindowService, globalHelper) {
        var self = this;
        this._super($scope);
        this._reportService = reportService;
        this._notificationService = notificationService;
        this._wizardSharedService = wizardSharedService;
        this._commonHelper        = commonHelper;
        this.globalHelper = globalHelper;

        this.$scope.modalWindow   = modalWindowService;
        this.$scope.paginator     = paginationService;

        this.$location = $location;

        self.$scope.Math = Math;

        self._commonHelper._setVIEWVariables(self.$scope);
        self.$scope.selectedCategories = [];
        self.$scope.reportCategories = ReportCategories;

        self.$scope.favouriteReports = [];
        reportService.favouriteList().then(function (response) {
            self.$scope.favouriteReports = response.data;
        })

        self.$scope.tabs = {
            options: {
                my: "My reports",
                ootb: "Default reports",
                others: "Reports made by others",
                build: "CFEngine Build"
            },
            selected: 'my',
            previouslySelected: ''
        };
        self.defaultSelectedCategoryPlaceholder =  'Category: All';
        self.$scope.selectedCategoryPlaceholder = self.defaultSelectedCategoryPlaceholder;
        self._refreshReportsList();
    },

    defineScope: function() {
        this.$scope.instance = "indexController";
        this.$scope.createNewReport = this.createNewReport.bind(this);
        this.$scope.deleteReport    = this.deleteReport.bind(this);
        this.$scope.cleanStoredScope= this.cleanStoredScope.bind(this);

        this.$scope.showAllReports  = this.showAllReports.bind(this);
        this.$scope.sortReorder     = this.sortReorder.bind(this);

        this.$scope.addFavourite     = this.addFavourite.bind(this);
        this.$scope.removeFavourite     = this.removeFavourite.bind(this);

        this.$scope.deleteConfirm   = this.deleteConfirm.bind(this);
        this.$scope.filterCategories = this.filterCategories.bind(this);
        this.$scope.isSelectedCategory  = this.isSelectedCategory.bind(this);

        this.$scope.getUserName  = this.getUserName.bind(this);
    },

    defineListeners: function() {
        var self = this;
        self.$scope.$on('paginatorChange', function() {
            self._refreshReportsList();
        });
        self.$scope.$watch('tabs.selected', function(newVal, oldVal) {
            self.$scope.tabs.previouslySelected = oldVal;
            self._refreshReportsList();
        });
    },
    /**
     *  Click on new report button
     */
    createNewReport: function(arg)
    {
        var self = this;
        // clear tmp local stored sql query
        self._wizardSharedService.resetScope();
        if (arg === 'inventory') {
            self.$location.path('/inventory');
        } else if (arg === 'changes') {
            self.$location.path('/changes');
        } else if (arg === 'fim') {
            self.$location.path('/file_integrity_monitoring');
        } else if (arg === 'compliance') {
            self.$location.path('/compliance');
        } else {
          self.$location.path('/custom/new');
        }
    },
    deleteReport: function(id) {
        var self = this;
        self.$scope.modalWindow.close();
        self._reportService.deleteReport(id).then(
            function(result) {
                self._notificationService.setNotification('success', result.data);
                self._refreshReportsList();
            },
            function(error) {
                self._notificationService.setNotification('error', error.data);
            });
    },

    deleteConfirm: function(reportId) {
        var self = this;
        self.$scope.selectedReport = reportId;
        self.$scope.modalWindow.open('deleteConfirm', self.$scope);
    },

    addFavourite: function (reportId) {
        var self = this;
        self._reportService.addFavourite(reportId).then(
            () => self.$scope.favouriteReports.push(reportId)
        )
    },

    removeFavourite: function (reportId) {
        var self = this;
        self._reportService.removeFavourite(reportId).then(
            () => self.$scope.favouriteReports = self.$scope.favouriteReports.filter(v => v != reportId)
        )
    },

    getUserName: function (row) {
        return this.globalHelper.getUserName(row.meta_data.source, row.username)
    },

    filterCategories: function(cat) {
        if (cat) {
            var index = this.$scope.selectedCategories.indexOf(cat);
            if (index !== -1) {
                this.$scope.selectedCategories.splice(index, 1);
            } else {
                this.$scope.selectedCategories.push(cat);
            }
        } else {
            this.$scope.selectedCategories = [];
        }

        this.$scope.selectedCategoryPlaceholder = (this.$scope.selectedCategories.length > 0) ?
            this.$scope.reportCategories
                .filter(item => this.$scope.selectedCategories.includes(item.value))
                .map(item => item.label)
                .join(', ') :
            this.defaultSelectedCategoryPlaceholder;

        this._refreshReportsList();
    },
    isSelectedCategory: function(cat) {
        var index = this.$scope.selectedCategories.indexOf(cat);
        return (index === -1) ? false : true;
    },

    /**
     * Query server for reports
     */
    _refreshReportsList: function() {
        var self = this;
        self.$scope.reports_loaded = false;
        self.$scope.savedReports  = {};

        var pagingData = $.param({
            page      : (self.$scope.paginator.page !== undefined ? self.$scope.paginator.page : 1),
            limit     : self.$scope.paginator.rowsPerPage,

            reportCategory: self.$scope.selectedCategories,
            sortColumn    : (self.$scope.VIEW.sortColumn     !== undefined && self.$scope.VIEW.sortColumn     != '' ? self.$scope.VIEW.sortColumn     : 'label'),
            sortDescending: (self.$scope.VIEW.sortDescending !== undefined && self.$scope.VIEW.sortDescending != '' ? self.$scope.VIEW.sortDescending : '0'),
            tab: self.$scope.tabs.selected
        });

        self._reportService.loadReports(pagingData).then(
            function(result) {
                var tmp = result.data;
                // if no reports on my tab and category filter was not applied then load default reports tab
                // and previously selected tab should not be changed, otherwise will look buggy when you click from default
                // reports to my and the UI will switch back
                if (
                    tmp.total == 0 &&
                    self.$scope.tabs.selected == 'my' &&
                    self.$scope.selectedCategories.length == 0 &&
                    self.$scope.tabs.previouslySelected == 'my'
                ) {
                    self.$scope.tabs.selected = 'ootb';
                    return;
                }

                self.$scope.savedReports  = tmp.items;
                self.$scope.paginator.refreshPaginator(tmp.total);
                if (self.$scope.paginator.page > self.$scope.paginator.pages) {
                    // if refreshing data causes current page to be outwith page range, reset page number
                    self.$scope.paginator.reloadView(self.$scope.paginator.pages);
                }
                self.$scope.reports_loaded = true;
            },
            function(error) {
                self._notificationService.setNotification('error', error.data);
                self.$scope.reports_loaded = true;
            });
    },

    cleanStoredScope: function() {
        this._wizardSharedService.resetScope();
    },

    showAllReports: function() {
        var self = this;
        self.$location.path('/allreports');
    },
// TODO: refactor
   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._refreshReportsList();
        }
    }
});

indexController.$inject = ['$scope', '$location', 'reportService', 'notificationService', 'wizardSharedService', 'paginationService', 'commonHelper', 'modalWindowService', 'globalHelper'];
