/*jslint node: true */
/*jslint browser: true*/
/*jslint nomen: true*/
/*jslint plusplus: true */
/*global BaseController, angular, DCA, bootbox*/

'use strict';

const TWO_FA_NOTIFICATION_KEY = 'disabled_two_fa_dashboard_notification_at';
const TWO_FA_NOTIFICATION_REMINDER_DURATION = 30 * 24 * 60 * 60 * 1000; // 30 days in milliseconds

var dashboardController = BaseController.extend({
	/**
     * Initialize  Controller
     * @param $scope, current controller scope
     */

    init: function (
        $scope,
        $q,
        $window,
        $location,
        $rootScope,
        $interval,
        $filter,
        $routeParams,
        dashboardHelper,
        widgetHelper,
        eventsLogService,
        modalWindowService,
        widgetService,
        alertsService,
        inventoryHelper,
        tourGuideHelper,
        welcomeWizardService,
        userService,
        reportService,
        profileService
    ) {
        var self = this;
        this._super($scope);

        this._$q       = $q;
        this.$location = $location;
        this.$filter = $filter;
        this.$window = $window;
        this._$routeParams = $routeParams;

        self._dashboardHelper    = dashboardHelper;
        self._widgetHelper       = widgetHelper;
        self._eventsLogService   = eventsLogService;
        self.$scope.modalWindow  = modalWindowService;
        self._widgetService      = widgetService;
        self._alertsService      = alertsService;
        self._inventoryHelper      = inventoryHelper;
        self._tourGuideHelper = tourGuideHelper;
        self.welcomeWizardService = welcomeWizardService;
        self.userService = userService;
        self.reportService = reportService;
        self.profileService = profileService;

        self.$scope.showTwoFaNotification = false;
        self._initTwoFaNotification();

        self.$scope.DCA  = DCA;

        self.$scope.Math = Math;

        self.$scope.widgets    = {};
        self.$scope.eventsLog  = {};
        self.$scope.widgetData = {};
        self.$scope.dashData = {};
        self.$scope.refreshingTime = 0;
        self.$scope.clickedInventory = false;
        self.$scope.inventoryAttributeValues = [{'value': '', 'name': 'Select an attribute'}];
        self.$scope.inventoryChartTypeValues = [
            {'value': '', 'name': 'Select chart type'},
            {'value': 'bar', 'name': 'Bar chart'},
            {'value': 'pie', 'name': 'Pie chart'},
            {'value': 'solidgauge', 'name': 'Solid gauge'},
            {'value': 'table', 'name': 'Table'}
        ];
        self.$scope.widgetData.chartType = '';
        self.$scope.widgetData.inventoryAttribute = '';
        self.$scope.widgetData.complianceReport = '';
        self.$scope.complianceReports = [];

        self.$scope.widgetTypes = ['changes', 'hostCount', 'alerts', 'inventory'];

        this.initSharedOptions();

        // Check if dashboardId is provided in URL
        self.$scope.dashboardIdFromUrl = self._$routeParams.dashboardId;

        self._getDashboards();

        self.$scope.currentPage = 0;
        self.$scope.pageSize = 50;

        $rootScope.$on('wizardUpdated_Event', function () {
            self._refreshDashboardWidgets();
        });

        $rootScope.$on('modalClose', function () {
           self.$scope.clickedInventory = false;
           self.$scope.clickedCompliance = false;
        });

        var refresh = $interval(function() {
            self._refreshDashboardWidgets();
        }, 300000);
        // 5 minute interval for refreshing


        self.$scope.$on('$destroy', function() {
          // Make sure that the interval is destroyed too
            if (angular.isDefined(refresh)) {
                $interval.cancel(refresh);
                refresh = undefined;
            }
        });
        self._checkCookies();

        self.$scope.$watch('welcomeWizardDisabled', function(val) {
            if (typeof val === 'boolean') {
                self.welcomeWizardService.changeSeenWizard(val === true ? 1 : 0);
            }
        });

        self.$scope.$watch('currentDash.name', function(val) {
            if (val) {
                if (val.length<8) {
                     self.$scope.shortName = true;
                 } else {
                    self.$scope.shortName = false;
                 }

            } else {
                self.$scope.shortName = false;
            }
        });

        self.$scope.sortableWidgets = {
            cancel: ".unsortable",
            items: "li:not(.unsortable)",
            stop: function() {
                // this callback has the changed model
                // SAVE WIDGETS NOW
                var newOrder = {};
                newOrder['widgets'] = [];
                angular.forEach(self.$scope.widgets, function(widget, index) {
                  newOrder['widgets'].push(widget.id);
                });
                self._dashboardHelper.reorderwidgets(newOrder, self.$scope.currentDash.id).then(
                    function (result) {
                        self._getDashboards();
                    }
                );
            },
            tolerance: "pointer",
            handle: ".bi-arrows-move",
            placeholder: "widget-placeholder"
        };

        self.$scope.seenTour = false;
        self.$scope.$watch('seenTour', function (newValue, oldValue) {
            if (oldValue != undefined && oldValue != newValue) {
                self._tourGuideHelper.changeSeenTour(newValue);
            }
        });

        $rootScope.$on('welcomeWizardClosed', function () {
            setTimeout(() => self.initTourGuide(), 1000);
        })

        self._dashboardHelper.getUserRoles().then((roles) => {
            self.$scope.noroles = roles.length == 0;
        })
    },

    defineListeners: function () {
        this.$scope.$watch('shared', (data) => {
            let sharedData = {users: [], roles: [], sharedWithAll: false};
            for (const type in data) {
                const values = data[type].selectedOptions;
                if (values !== undefined) {
                    for (const value of values) {
                        if (value.id == 'all') {
                            sharedData['sharedWithAll'] = true;
                        } else {
                            sharedData[type].push(value.name.toString());
                        }
                    }
                }
            }
            this.$scope.dashData.sharedWith = sharedData;
        }, true);

        $('body').on('DARK_THEME_CHANGED', () => this._getDashboards()); // reload widgets on theme change to apply new colors
    },

    defineScope: function () {
        this.$scope.instance            = "dashboardController";
        this.$scope.viewWidgetInfo      = this.viewWidgetInfo.bind(this);

        this.$scope.deleteWidget        = this.deleteWidget.bind(this);
        this.$scope.createWidget        = this.createWidget.bind(this);
        this.$scope.highlightWidgets    = this.highlightWidgets.bind(this);

        this.$scope.createDashboard     = this.createDashboard.bind(this);
        this.$scope.selectDashboard     = this.selectDashboard.bind(this);
        this.$scope.removeDashboard     = this.removeDashboard.bind(this);
        this.$scope.cloneDashboard      = this.cloneDashboard.bind(this);
        this.$scope.copyData            = this.copyData.bind(this);
        this.$scope.cloneData           = this.cloneData.bind(this);

        this.$scope.saveOldName         = this.saveOldName.bind(this);
        this.$scope.editName            = this.editName.bind(this);

        this.$scope.getPriorityNumbers  = this.getPriorityNumbers.bind(this);
        this.$scope.addWidget           = this.addWidget.bind(this);
        this.$scope.addInventoryWidget  = this.addInventoryWidget.bind(this);
        this.$scope.addComplianceWidget  = this.addComplianceWidget.bind(this);
        this.$scope.initInventoryForm   = this.initInventoryForm.bind(this);
        this.$scope.initTourGuide    = this.initTourGuide.bind(this);
        this.$scope.initComplianceForm = this.initComplianceForm.bind(this);
        this.$scope.saveDashboardTitle = this.saveDashboardTitle.bind(this);
        this.$scope.hideTwoFaNotification = this.hideTwoFaNotification.bind(this);

    },

    initSharedOptions: function() {

        this.$scope.shareWithAll = {name: "All users", id: "all"};

        this.$scope.shared = {
            users: {
                selectedOptions: [this.$scope.shareWithAll],
                options: [this.$scope.shareWithAll]
            },
            roles: {
                selectedOptions: [],
                options: []
            }

        };

        this.userService.getUsers().then((result) => {
            for (const user of result.data) {
                this.$scope.shared.users.options.unshift({
                    name: user.id,
                    id: 'users_' + user.id
                });
            }
        });

        this.userService.getRoles().then((result) => {
            for (const role of result.data) {
                this.$scope.shared.roles.options.unshift({
                    name: role.id,
                    id: 'roles_' + role.id
                });
            }
        });
    },

    highlightWidgets: function (id) {

        var self = this, x = 0, i = 0, widget;

        if (!self.$scope.widgets) {
            return;
        }

        for (x = 0; x < self.$scope.widgets.length; x++) {
            widget = self.$scope.widgets[x];
            widget.isActive = false;

            if (widget.alerts && id) {
                for (i = 0; i < widget.alerts.length; i++) {
                    // white space appearing in every second alert id here !!
                    if (id === widget.alerts[i].replace(/ /g,'')) {
                        widget.isActive = true;
                        break;
                    }
                }
            }
        }
    },

    _refreshDashboardWidgets: function () {
        var self = this, data = {};
        data.alerts = [];
        self._refreshSubsetWidgets().then(function (result) {
            // got self.scope.widgets for current dashboard
            angular.forEach(self.$scope.widgets, function({alerts = []}) {
                data.alerts = [...data.alerts, ...alerts.map(Number)];
            });

            data.limit = 10;
            self._eventsLogService.getdasheventslog(data).then(function (result) {
                self.$scope.eventsLog = result.data;
                self.$scope.eventsLogLoaded = true;
                    if (angular.equals({},self.$scope.eventsLog)) {
                        self.$scope.eventsLog = null;
                    }
                },
                function (error) {
                    // TODO:
                    // Error notification
                }
            );
        });
    },


    viewWidgetInfo: function (widget) {
        var self = this;
        self._widgetService.saveWidgetData(widget);
        self.$location.path("alerts/listAll");
    },


    createWidget: function (singleAlert = false) {
        var self = this;
        self.$scope.widgetData.singleAlert = singleAlert;
        self._widgetHelper.getwidgetwithname(self.$scope.widgetData.name, self.$scope.widgets).then(
            function (result) {
                if (result) {
                    //already exists
                    self.$scope.$emit('saveWidget_Fail_Event', "A widget with this name already exists");
                } else {
                    // save widgetdata and go to alert page
                    self._widgetService.saveWidgetData(self.$scope.widgetData);
                    self.$location.path('alerts/add');
                    self.$scope.modalWindow.close();
                }
            },
            function (error) {
                // error handled on helper level
            }
        );
    },

    addWidget: function (type, name) {
        var self = this;
        self._widgetHelper.getwidgetsbytype(type).then(
            function (result) {
                if (!result || !self.$scope.widgetlist.length) {
                    self.$scope.widgetData = {};
                    self.$scope.widgetData.type = type;
                    self.$scope.widgetData.name = name;
                    self._widgetHelper.savewidget(self.$scope.widgetData).then(
                        function (result) {
                            if (result.data[0].widgetId) {
                                self._dashboardHelper.addwidget(result.data[0].widgetId).then(
                                    function (result) {
                                        self._getDashboards();
                                    }
                                );
                            }
                        },
                        function (error) {
                            notify.error(error.data);
                            console.log(error);
                        }
                    );
                    self.$scope.modalWindow.close();
                }
            }
        );
    },

    addInventoryWidget: function () {
        var self = this;
                    self.$scope.widgetData.type = "inventory";
                    self.$scope.widgetData.name = self.$scope.widgetData.name || self.$scope.widgetData.inventoryAttribute;
                    self.$scope.widgetData.errors = [];

                    self.$scope.widgetData.inventoryAttribute == '' &&
                        self.$scope.widgetData.errors.push('The inventory attribute cannot be blank.');

                    self.$scope.widgetData.chartType == '' &&
                       self.$scope.widgetData.errors.push('The chart type cannot be blank.')

                    if(self.$scope.widgetData.errors.length > 0){
                        return;
                    }

        this.saveWidget();
    },

    addComplianceWidget: function () {
        var self = this;
        let complianceReportName;
        self.$scope.widgetData.errors = [];

        self.$scope.widgetData.complianceReport == undefined &&
        self.$scope.widgetData.errors.push('The compliance report cannot be blank.');

        self.$scope.complianceReports.forEach(item => {
            if (item.value == self.$scope.widgetData.complianceReport) {
                complianceReportName = item.name;
            }
        });

        self.$scope.widgetData.type = "compliance";

        self.$scope.widgetData.name = self.$scope.widgetData.name || complianceReportName;

        if(self.$scope.widgetData.errors.length > 0){
            return;
        }
        this.saveWidget();
    },
    saveWidget: function () {
        let self = this;
        const payload = JSON.stringify(self.$scope.widgetData);
        self.$scope.widgetData.payload = payload;
        self._widgetHelper.savewidget(self.$scope.widgetData).then(
            function (result) {
                if (result.data[0].widgetId) {
                    self._dashboardHelper.addwidget(result.data[0].widgetId).then(
                        function (result) {
                            self._getDashboards();
                            self.$scope.modalWindow.close();
                            self.$scope.clickedInventory = false;
                        }
                    );
                }
            },
            function (error) {
                self.$scope.widgetData.errors.push(error.data);
            }
        );
    },

    deleteWidget: function (widgetData) {
        var self = this;
        $("<div></div>")
            .dialog_modal({
                passedArgs: ["Remove the widget '" + widgetData.name + "' from the dashboard?", [
                    //buttons
                    {
                        "label": "Cancel",
                        "class": "btn-large"
                    },
                    {
                        "label": "Remove",
                        "class": "btn-large btn-primary btn-danger",
                        "callback": function () {

                            self._widgetHelper.deletewidget(widgetData.id).then(
                                function (result) {
                                    self._dashboardHelper.deletewidget(widgetData.id).then(
                                        function (result) {
                                            self._getDashboards();
                                        },
                                        function (error) {
                                            // error handled on helper level
                                        }
                                    );
                                },
                                function (error) {
                                    // error handled on helper level
                                }
                            );
                        }
                    }
                ],
                    {
                        header: "<h2>Remove widget</h2>"
                    }],
            });
    },

    saveOldName: function(name) {
        var self = this;
        self.$scope.oldName = name;
    },

    editName: function (widget) {
        var self = this;

        if (widget.name !== self.$scope.oldName) {
            self._widgetHelper.savewidget(widget).then(
                function (result) {
                    self.$scope.$emit('saveWidget_Success_Event');
                    self._refreshDashboardWidgets();
                },
                function (error) {
                // TODO:
                // Error notification
                self.$scope.$emit('saveWidget_Fail_Event', error.data);
            });
        }
    },

    saveDashboardTitle: function () {
        let deferred = this._$q.defer();
        this._dashboardHelper.savedashboard({id: this.$scope.currentDash.id, name: this.$scope.currentDash.name}).then(
            () => {
                this._dashboardHelper.getdashboards().then(result => this.$scope.dashboards = result);
                deferred.resolve();
            },
            error => deferred.reject(error)
        );
        return deferred.promise;
    },

    getPriorityNumbers: function(stats) {
        if (stats) {
            if (stats.high.failAlerts) {
                return {'alerts':stats.high.failAlerts,'hosts':stats.high.failHosts};
            } else if (stats.medium.failAlerts) {
                return {'alerts':stats.medium.failAlerts,'hosts':stats.medium.failHosts};
            } else if (stats.low.failAlerts) {
                return {'alerts':stats.low.failAlerts,'hosts':stats.low.failHosts};
            }
        }

    },

    _checkCookies: function () {
        var self = this;

        self.welcomeWizardService.getSeenWizard().then(function (data) {
            self.$scope.seenWizard = data.data.seen_wizard;
            if (self.$scope.seenWizard !== 1 && sessionStorage.seen_wizard == 'false' && modalThreshold.canBeShown()) {
                //no cookie & new session: show modal
                sessionStorage.seen_wizard = true;
                self.$scope.showModal = true;
            } else {
                self.initTourGuide();
            }
        });
    },

    _initTwoFaNotification: function () {
        var self = this;

        self.profileService.getAdditionalData(TWO_FA_NOTIFICATION_KEY).then(function (response) {
            var disabledAt = Number(response.data);
            // skip if the notification was dismissed within the last month
            if (disabledAt && (Date.now() - disabledAt) < TWO_FA_NOTIFICATION_REMINDER_DURATION) {
                return;
            }
            self.profileService.getUser().then(function (response) {
                self.$scope.showTwoFaNotification = !response.data.two_factor_enabled;
            });
        });
    },

    hideTwoFaNotification: function () {
        var self = this;
        self.$scope.showTwoFaNotification = false;
        self.profileService.setAdditionalData(TWO_FA_NOTIFICATION_KEY, Date.now());
    },

    initTourGuide: function () {
        var self = this;
        if(localStorage.getItem('tourPaused') === 'true'){
            sessionStorage.setItem('tour_session_initialized', 'true')
        }
        self._tourGuideHelper.getTourSeen().then(function (data) {
            if (
                data.data.seen_tour == 0 &&
                sessionStorage.getItem('tour_session_initialized') == 'false' &&
                modalThreshold.canBeShown()
            ) {
                self.$scope.showTourModal = true;
                sessionStorage.setItem('tour_session_initialized', 'true');
            }
        });
    },

    createDashboard: function(overwrite) {
        // also used for editing dashboards
        var self = this;
        var starting;

        self.$scope.newDash = {};
        if (!overwrite) {
            starting = self.$scope.dashData.starting;
        }
        angular.copy(self.$scope.dashData, self.$scope.newDash);

        self._dashboardHelper.savedashboard(self.$scope.newDash).then(
            function (response) {
                var result = response.data;
                if (!self.$scope.newDash.id) {
                    self.$scope.newDash.id = result[0].dashboardId;
                }
                self.$scope.modalWindow.close();
                self.$scope.dashData = result[0];
                self._dashboardHelper.getdashboards().then(
                    function (result) {
                        self.$scope.dashboards = result;
                        self.$scope.selectDashboard(self.$scope.newDash.id).then(
                            function (result) {
                                if (starting === true) {
                                    // create copies of default widgets and add ids to this dash
                                    self._setDefaultWidgets(self.$scope.newDash.id).then(
                                        function (result) {
                                            self.$scope.dashData.widgets = result.join();
                                            self.$scope.createDashboard(true);
                                        },
                                        function (error) {
                                            notify.error(error.data);
                                        }
                                    );
                                }
                            });
                    });
            },
            function (error) {
                self.$scope.$emit('saveDashboards_Fail_Event', error.data);
            });

    },

    _setDefaultWidgets: function (dashId) {
        var self = this;
        var promises = [];
        // get default widgets + alerts and make copies, then save ids

        angular.forEach(self.$scope.DCA.Default_widgets, function (widget, index) {
            var widgetObj = angular.copy(widget);
            delete widgetObj['alert'];
            widgetObj.alerts = "";
            widgetObj.dashboardid = dashId;

            const saveAlert = (alertObj, widgetId, widgetName) => {
                alertObj.widgetid = widgetId;
                alertObj.widgetname = widgetName;
                self._alertsService.savealert(alertObj);
            }

            var promise = self._widgetHelper.savewidget(widgetObj, true).then(
                function (result) {
                    if (!angular.equals({}, widget.alert)) {
                        if (Array.isArray(widget.alert)) {
                            widget.alert.map(alert => saveAlert(alert, result.data[0].widgetId, widgetObj.name));
                        } else {
                            saveAlert(widget.alert, result.data[0].widgetId, widgetObj.name);
                        }
                    }
                    return result.data[0].widgetId;
                },
                function (error) {
                    console.log("error", error);
                    // handle error
                }
            );
            promises.push(promise);
        });
        return self._$q.all(promises);
    },

    _getDashboards: function () {
        var self = this;

        self._dashboardHelper.getdashboards().then(
            function (result) {
                self.$scope.dashboards = result;
                self._getSelectedDashboard();
            },
            function (error) {
                // error handling
                // console.log("error");
            }
        );

    },

    selectDashboard: function (dash_id) {
        var self = this;
        return self._dashboardHelper.setselecteddashboard(dash_id).then(
            function (result) {
                self.$scope.widgetlist = self._getWidgetsForDash(result.dashboard);
                self._refreshDashboardWidgets();
                return result;
            },
            function (error) {
                // handle error
            }
        );
    },

    _getWidgetsForDash: function (dash_id) {
        var self = this;
        // get widget list of specified dash
        var current_dash = {};
        if (dash_id !== undefined) {
            current_dash = self.$filter('filter')(self.$scope.dashboards, function (d) {return d.id == dash_id})[0];
        } else {
            current_dash = self.$scope.dashboards[0];
        }

        // Check if dashboard exists and user has access
        if (!current_dash) {
            self.$window.location.href = '/error404';
            return [];
        }

        self.$scope.currentDash = angular.copy(current_dash);
        self.$scope.copyData(current_dash);
        return current_dash.widgets;
    },

    _getSelectedDashboard: function () {
        var self = this;
        var id;
        if (self.$scope.dashboards) {
            id = self.$scope.dashboards[0].id;
        }

        if (self.$scope.dashboardIdFromUrl) {
            id = self.$scope.dashboardIdFromUrl;

            // Check if dashboard exists in user's accessible dashboards
            var dashboardExists = self.$filter('filter')(self.$scope.dashboards, function (d) {return d.id == id}).length > 0;

            if (!dashboardExists) {
                self.$window.location.href = '/error404';
                return;
            }

            // set it as the selected dashboard for the user
            self.$scope.selectDashboard(id);
            self.$scope.widgetlist = self._getWidgetsForDash(id);
            self._refreshDashboardWidgets();
            return;
        }

        // get user list from db, if current user is there and has a selected dash, get its ID
        // other wise don't set id, take first dash in list as default (?)
        self._dashboardHelper.getselecteddashboard().then(
            function (result) {
                self.$scope.currentUser = result[0].username;
                if (result[0].dashboard) {
                    id = result[0].dashboard;
                } else {
                    self.$scope.selectDashboard(id);
                }
                self.$scope.widgetlist = self._getWidgetsForDash(id);
                self._refreshDashboardWidgets();
            },
            function (error) {
                // handle error
            }
        );
    },

    _refreshSubsetWidgets: function () {
        // THIS SHOULD REPLACE THE CURRENT REFRESH THING ## FIX
        var self = this;

        // set widgets from list of dash widgets
        return self._widgetHelper.getdashboardwidgetswithalerts(self.$scope.widgetlist).then(
            function(result) {
                var orderedWidgets = []
                self.$scope.widgetlist.forEach(function (v) {
                    var widget = $.grep(result, function(e){ return e.id == v; })[0];
                    if (widget != undefined) {
                        orderedWidgets.push($.grep(result, function(e){ return e.id == v; })[0]);
                    }
                });
                // get widgets
                self.$scope.widgets = orderedWidgets;
                self.$scope.widgets.forEach(function (value,key) {
                    self.$scope.widgets[key].payload = JSON.parse(value.payload);
                })
                self.$scope.refreshingTime = Date.now();
                setClickedAlert();
                return;
            },
            function(error) {

            })


        function setClickedAlert () {
            self.$scope.clickedAlert = false;
            self.$scope.clickedSingleAlert = false;
            self.$scope.clickedChanges = false;
            self.$scope.clickedHostCount = false;
            self.$scope.clickedDecommissionedHosts = false;
            self.$scope.clickedFileChanges = false;
            self.$scope.clickedNotKeptNeverRepaired = false;
            self.$scope.clickedInventory = false;
            angular.forEach(self.$scope.widgets, function(widget) {
                if(widget !== undefined){
                switch (widget.type){
                    case 'changes':
                        self.$scope.clickedChanges = true;
                        break;
                    case 'clickedSingleAlert':
                        self.$scope.clickedSingleAlert = true;
                        break;
                    case 'hostCount':
                        self.$scope.clickedHostCount = true;
                        break;
                    case 'decommissionedHosts':
                        self.$scope.clickedDecommissionedHosts = true;
                        break;
                    case 'fileChanges':
                        self.$scope.clickedFileChanges = true;
                        break;
                    case 'notKeptNeverRepaired':
                        self.$scope.clickedNotKeptNeverRepaired = true;
                        break;
                    }
                }
            });

        }
    },


    removeDashboard: function (dash_id) {
        var self = this;
        self._dashboardHelper.removedashboard(dash_id).then(
            function (result) {
                self.$scope.modalWindow.close();
                // REFRESH DASH LIST
                self._getDashboards();
                // REMOVE FROM USER's selected

                // select other  dashboard if needed
            },
            function (error) {
                console.log(error);
            }
        );
    },

    cloneDashboard: function (dashboard) {
        try {
            let self = this;
            self._dashboardHelper.cloneDashboard(dashboard).then(
                (result) => {
                    self.$scope.modalWindow.close();
                    // refresh dashboards list
                    self._getDashboards();
                    // select dashboard
                    self.$scope.selectDashboard(result.data);
                }, (error) => {
                    self.$scope.$emit('saveDashboards_Fail_Event', error.data);
                }
            );
        } catch (error) {
            notify.error(error.toString());
            throw error;
        }
    },

    copyData: function (data) {
        var self = this;
        self.$scope.dashData = angular.copy(data);
        self.$scope.isChecked = self.$scope.dashData.public === 1;
        this.selectSharedOptions();
    },

    selectSharedOptions: function () {
        let result = {users: [], roles: []};
        if (this.$scope.dashData.sharedWith === undefined) {
            result.users.push(this.$scope.shareWithAll);
        } else {
            for (const type in this.$scope.dashData.sharedWith) {
                const value = this.$scope.dashData.sharedWith[type];
                if (type == 'sharedWithAll' && value === true) {
                    result.users.push(this.$scope.shareWithAll);
                } else {
                    if (Array.isArray(value)) {
                        for (const v of value) {
                            result[type].push({id: `${type}_${v}`, name: v});
                        }
                    }
                }
            }
        }
        this.$scope.shared.users.selectedOptions = result.users;
        this.$scope.shared.roles.selectedOptions = result.roles;
    },

    cloneData: function (data) {
        var self = this;
        self.$scope.dashData = angular.copy(data);
        self.$scope.dashData.name = 'Copy of ' + self.$scope.dashData.name;
        self.$scope.isChecked = false;
        self.$scope.dashData.public = false;
    },

    initInventoryForm: function (type) {
        var self = this;
        self.$scope.clickedInventory = true;
        self.$scope.widgetData = {};
        self.$scope.widgetData.chartType = type;
        if(self.$scope.inventoryAttributeValues.length <= 1){
            self._inventoryHelper.getInventoryVariables().then(
                function (result) {
                    // alphabetize inventory attribute list
                    result.InventoryItems.grouped.sort((x, y) => (x.label > y.label) ? 1 : -1)
                    result.InventoryItems.grouped.forEach(function (item) {
                        self.$scope.inventoryAttributeValues.push({'value' : item.label, 'name': item.label, 'category': item.category});
                    })
                }
            );
        }
    },
    initComplianceForm: function () {
        var self = this;
        self.$scope.clickedCompliance = true;
        self.$scope.widgetData = {};
        if (self.$scope.complianceReports.length == 0) {
            let params = $.param({
                page: 1,
                limit: 0,
                reportCategory: self.$scope.selectedCategories,
                sortColumn: 'label',
                sortDescending: '0',
                type: 'compliance',
                isPublic: 1
            });

            self.reportService.loadReports(params).then(
                function (result) {
                    result.data.items.forEach(function (item) {
                        self.$scope.complianceReports.push({'value': item.id, 'name': item.label});
                    })
                    self.$scope.complianceReports.push([])
                },
                function () {
                    notify.error('Compliance reports cannot be loaded. Please check the application logs.');
                });
        }
    }

});

dashboardController.$inject = [
    '$scope',
    '$q',
    '$window',
    '$location',
    '$rootScope',
    '$interval',
    '$filter',
    '$routeParams',
    'dashboardHelper',
    'widgetHelper',
    'eventsLogService',
    'modalWindowService',
    'widgetService',
    'alertsService',
    'inventoryHelper',
    'tourGuideHelper',
    'welcomeWizardService',
    'userService',
    'reportService',
    'profileService'
];

window.dashboardController = dashboardController;
