angular
    .module('complianceWidgetDirective', [])
    .directive('complianceWidget',
        [
            'complianceWidgetHelper', 'reportService', 'rulesService', 'complianceHelper',
            function (complianceWidgetHelper, reportService, rulesService, complianceHelper) {
                return {
                    templateUrl: MP_SITE_URL + '/dashboard/partials/compliance_widget',
                    restrict: 'A',
                    scope: {
                        widget: '=',
                        currentUser: '=',
                        currentDash: '=',
                        saveOldName: '&',
                        editName: '&',
                        deleteWidget: '&',

                    },
                    link: function (scope, element) {
                        scope.$watch(function () {
                            return element.attr('refresh');
                        }, function () {
                            scope.conditions = undefined;
                            scope.totalScore = undefined;
                            reportService.getTotalHostsCount().then(count => {
                                scope.totalHostsCount = count;
                            });
                            reportService.loadReport(scope.widget.payload.complianceReport).then(
                                function (result) {
                                    let data = result.data;
                                    let reportData = angular.fromJson(data.AdvancedReportsData.SQL ?? '');
                                    scope.totalChecks = reportData.conditions.length;

                                    reportService.getTotalHostsCount().then(count => {
                                        scope.totalCount = count;
                                        if (scope.totalChecks > 0) {
                                            rulesService.getrules(reportData.conditions).then(res => {
                                                scope.totalPass = 0;
                                                scope.conditions = res.data;
                                            });
                                        }
                                    })
                                });
                        });

                        scope.$watch('conditions', () => {
                            let totalConditionsHosts = 0;
                            let totalHostsPassed = 0;
                            if (scope.conditions !== undefined) {
                                let i = 0;
                                scope.conditions.forEach((condition, key) => {
                                    rulesService.getStats(condition.id).then(function (data) {
                                        i++;
                                        scope.conditions[key].fail = data.data.failHosts;
                                        let totalHosts = parseInt(data.data.total === null ? scope.totalHostsCount : data.data.total);
                                        totalHostsPassed += (totalHosts - data.data.failHosts);
                                        totalConditionsHosts += totalHosts;
                                        if (i == scope.totalChecks) {
                                            scope.totalScore = complianceHelper.getComplianceScore(totalHostsPassed, totalConditionsHosts);
                                        }
                                    });
                                })
                            }
                        });

                        scope.$watch('totalScore', () => {
                            if (scope.totalScore !== undefined) {
                                const severityMap = Object.keys(DCA.RuleSeverity).reduce((map, key) => {
                                    map[DCA.RuleSeverity[key].value] = DCA.RuleSeverity[key].order;
                                    return map;
                                }, {});
                                scope.conditions.sort((a, b) => {
                                    if (severityMap[a.severity] > severityMap[b.severity]) {
                                        return -1;
                                    } else if (severityMap[a.severity] == severityMap[b.severity]) {
                                        return b.fail - a.fail;
                                    } else {
                                        return 1;
                                    }
                                }); // sort by severity and failed hosts
                                scope.chartList = complianceWidgetHelper.getChartData(scope.totalScore, scope.totalChecks, scope.totalCount);
                            }
                        })
                    }
                };
            }]);
