/*jslint node: true */
/*jslint browser: true*/
/*jslint nomen: true*/
/*jslint plusplus: true */
/*global dashboardApp, angular, $*/

'use strict';

dashboardApp.factory('widgetHelper',
            ['$rootScope', '$location', '$q', 'widgetwizardService', 'alertsService', 'changesService',
    function ($rootScope,   $location,   $q,   widgetwizardService,   alertsService, changesService ) {
            var helper = {};

            helper.getwidgetswithalerts = function (widgetId, dashboard = null) {
                return widgetwizardService.getwidgets(widgetId, dashboard).then(
                    function (result) {
                        return result.data;
                    },
                    function (error) {
                        // show error only if widget id is set
                        if (widgetId) {
                            $rootScope.$emit('getWidgets_Fail_Event', error.data);
                        }
                    }
                );
            };

        helper.getdashboardwidgetswithalerts = function (widgetIds) {
            // new function for 3.7 dashboard sharing - get widgets from a list of ids
            return widgetwizardService.getwidgets().then(
                function (result) {
                    return result.data;
                },
                function (error) {
                    // show error only if widget id is set
                    if (value) {
                        $rootScope.$emit('getWidgets_Fail_Event', error.data);
                    }
                }
            );
        };


            helper.getAlertStatsBySeverity = function (alertList) {
                return alertsService.getAlertStatsBySeverity(alertList).then(
                    function (result) {
                        return result.data;
                    },
                    function (error) {
                        $rootScope.$emit('getwidgetStats_Fail_Event', error.data);
                    }
                );
            };

            helper.getwidget = function (widgetId) {
                return widgetwizardService.getwidgets(widgetId).then(
                    function (result) {
                        return (result.data[0]);
                    },
                    function (error) {
                        // error handled on calling function
                        $rootScope.$emit('getWidgets_Fail_Event', error.data);
                    }
                );
            };

            helper.getwidgetwithname = function (widgetname) {
                return widgetwizardService.getwidgets().then(
                    function (result) {
                        var found = false;
                        result.data.forEach(function(widget) {
                            if (widget.name.toLowerCase() === widgetname.toLowerCase()) {
                                found = true;
                            }
                        });
                        return found;
                    },
                    function (error) {
                        // error handled on calling function
                        $rootScope.$emit('getWidgets_Fail_Event', error.data);
                    }
                );

            };

            /*
             * Return array of widgets by type. Useful for getting uneditable changes widget 3.7.0
             */
            helper.getwidgetsbytype = function (type) {
                return widgetwizardService.getwidgets().then(
                    function (result) {
                        var found = false;
                        result.data.forEach(function(widget) {

                            if (widget.type === type) {
                                found = true
                            }
                        });
                        return found;
                    },
                    function (error) {
                        // error handled on calling function
                        $rootScope.$emit('getWidgets_Fail_Event', error.data);
                    }
                );

            };


            helper._calculateComplianceDataByWidget = function (widgets) {

                var alertData = {}, alert = {"failHosts": 0, "totalHosts": 0, "lastStatusChange": 999999999999, "severity": ""};

                if (angular.equals({}, widgets)) {
                    return;
                }

                widgets.forEach(function (widget) {

                    alertData = helper.findCheckToShow(widget.alerts);
                    if (alertData.failHosts) {
                        // Need better error handling
                        widget.failHosts = alertData.failHosts;
                        widget.lastStatusChange = alertData.lastStatusChange;
                        widget.severity = alertData.severity;
                        widget.alertName = alertData.name;
                        widget.totalHosts = alertData.totalHosts;
                    } else {
                        // TODO: Error handling?
                        widget.failHosts = alert.failHosts;
                        widget.lastStatusChange = alert.lastStatusChange;
                        widget.severity = alert.severity;
                        widget.alertName = alert.name;
                        widget.totalHosts = alert.totalHosts;
                    }
                });

                return widgets;
            };

            helper.findCheckToShow = function(alertsArray) {
                /*
                 * Can refactor this
                 * finds the most recent failing alert of the highest priority
                 */
                var  h = [], m = [], l = [], alert = {"failHosts": 0, "totalHosts": 0, "lastStatusChange": 999999999999, "severity": ""};

                angular.forEach(alertsArray, function (alert, index) {
                    if (alert.failHosts) {
                        switch (alert.severity) {
                        case "high":
                            h.push(alert);
                            break;
                        case "medium":
                            m.push(alert);
                            break;
                        case "low":
                            l.push(alert);
                            break;
                        }
                    }
                });

                if (h.length > 0) {
                    //sort by most recent
                    alert = h[0];

                } else if (m.length > 0) {
                    //sort by most recent
                    alert = m[0];
                } else if (l.length > 0) {
                    //sort by most recent
                    alert = l[0];
                }
                return alert;
            };

            helper.savewidget = function (widgetObj) {
                if (!widgetObj) {
                    $rootScope.$emit('saveWidget_Fail_Event', 'widget data not set');
                    return false;
                }
                return widgetwizardService.savewidget(widgetObj);
            };

            helper.deletewidget = function (widgetId) {
                if (widgetId === undefined) {
                    $rootScope.$emit('deleteWidget_Fail_Event', 'Widget cannot be deleted - widget ID not set.');
                    return false;
                }
                return widgetwizardService.deletewidget(widgetId).then(
                    function (result) {
                        $rootScope.$emit('deleteWidget_Success_Event');
                        return result;
                    },
                    function (error) {
                        $rootScope.$emit('deleteWidget_Fail_Event', error.data);
                    }
                );
            };


            helper.loadWidgetAndAlertsWithRuleData = function (widgetId) {
                var deferred = $q.defer(), resultObject  = {};

                resultObject.widgetData = {};
                resultObject.widgetAlerts = {};

                widgetwizardService.getwidgets(widgetId).then(
                    function (result) {
                        resultObject.widgetData = result.data[0];
                        // Get widget alerts
                        if (result.data[0]['alerts'].length > 0) {
                            alertsService.getalertswithrule(result.data[0]['alerts']).then(
                                function (resultAlerts) {
                                    resultObject.widgetAlerts = resultAlerts.data;
                                    deferred.resolve(resultObject);
                                },
                                function (errorAlerts) {
                                    // Error notification
                                    return deferred.reject(errorAlerts);
                                }
                            );
                        } else {
                            deferred.resolve(resultObject);
                        }
                    },
                    function (error) {
                        // error handled on calling function
                        return deferred.reject(error);
                    }
                );

                return deferred.promise;
            };



            helper.reorderWidgets = function(data) {
                return widgetwizardService.reorderwidgets(data).then(
                        function(result) {
                            return true;
                        },
                        function(error) {
                           $rootScope.$emit('reorderWidgets_Fail_Event', error.data);
                        }
                );
            };

            helper.getChangesStats = function (data) {
                var deferred = $q.defer(), resultObject  = {};
                changesService.getChangesStats(data).then(
                    function (result) {
                        resultObject = result.data;
                        deferred.resolve(resultObject);
                    },
                    function (error) {
                         // Error notification
                        return deferred.reject(error);
                    }
                );
                return deferred.promise;
            };


            return helper;
        }]);