'use strict';

angular.module('complianceHelperModule', []).factory('complianceHelper', ['complianceWidgetHelper', function (complianceWidgetHelper) {
    let helper = {};

    const colors = {
        green: "#079649",
        red: "#D74936",
        orange: "#f89406",
        gray: "#333333",
        lightGray: "#e2e2e2",
        white: "#fff",
        backgroundGray: "#21262a",
    };

    helper.overallConfig = function (stats) {
        if (stats.totalHosts == undefined) {
            return false;
        }

        let config = complianceWidgetHelper.getChartData(
            this.getComplianceScore(stats.total.passedHosts, stats.total.hosts), stats.totalChecks, stats.totalHosts
        );
        const label = {
            labels: {
                    items: [{
                        html: 'Overall compliance',
                        style: {"color": this.getChartsTextColor(), "fontSize": "18px", "fontWeight": "bold", left: '0px',
                            top: '0px'},
                        align: 'left'
                    }]
                }
        };
        config = {...config, ...label};
        config.plotOptions.pie.center = ['50%', '50%'];
        config.plotOptions.pie.size = '140px';

        config.title.align = 'center';
        config.title.x = 0;
        config.title.y = 14;

        return config;
    };

    helper.categoriesConfig = function (stats) {
        let data = [];
        for (const category in stats.categories) {
            const val = this.getComplianceScore(stats.categories[category].totalPassedHosts, stats.categories[category].totalHosts);
            data.push({y: val, color: this.getColor(val), name: `${category}: ${val}%`});
        }

        let config = {
            chart: {
                type: 'bar',
                backgroundColor: this.getBackgroundColor()
            },
            exporting: {enabled: false},
            title: {
                text: 'Compliance by category',
                style: {"color": this.getChartsTextColor(), "fontSize": "18px",  "fontWeight": "bold", 'textTransform': 'none'},
                align: 'left',

            },
            credits: {
                enabled: false
            },
            noData: {
                style: {
                    fontSize: '12px',
                }
            },
            tooltip: {
                formatter: function () {
                    return '<span style="font-size: 14px"><b>' + this.x.substring(0, this.x.lastIndexOf(":")) + '</b></br>Compliance: ' + this.y +  '%</span>'
                },
                headerFormat: '<span style="font-size: 14px"><b>{point.key}</b></span><br/>',
                style: {
                    fontSize: '12px',
                },
                outside: true,
            },
            xAxis: {
                categories: data.map(item => item.name),
                labels: {
                    formatter: function (){
                        const label = this.axis.defaultLabelFormatter.call(this);
                        return label.substring(0, label.lastIndexOf(":"));
                    },
                    style: {
                        fontSize: '12px',
                        color: this.getChartsTextColor()
                    }
                }
            },
            yAxis: {
                min: 0,
                max: 100,
                labels: {
                    style: {
                        fontSize: '12px'
                    }
                },
                title: {
                    text: ''
                }
            },
            legend: {
                enabled: false,
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    stacking: 'normal'
                }
            },
            series: [{
                name: 'Compliance percentage',
                data: data,
            }]
        };
        return config;
    };

    helper.getColor = function (v) {
        let color = '';
        if (v >= 0 && v <= 20) {
            color = colors.red;
        } else if (v > 25 && v <= 75) {
            color = colors.orange;
        } else {
            color = colors.green
        }
        return color;
    };

    helper.getColorClass = function (v) {
        let className = '';
        if (v >= 0 && v <= 50) {
            className = 'important'
        } else if (v > 50 && v <= 75) {
            className = 'warning';
        } else {
            className = 'success';
        }
        return className;
    };

    helper.getChartsTextColor = function() {
        return  $('body').hasClass('dark') ? colors.lightGray : colors.gray;
    }

    helper.getBackgroundColor = function() {
        return  $('body').hasClass('dark') ? colors.backgroundGray : colors.white;
    }

    helper.getComplianceScore = function(passedHosts, allHosts) {
        // if no hosts then return 100 as fully compliant
        if (allHosts == 0) {
            return 100;
        }

        let percentage = Math.round(passedHosts / allHosts * 100);

        // if percentage ends up at 0% but there are some passing checks and it was rounded down, put 1% instead.
        if (percentage == 0 && passedHosts > 0) {
            percentage = 1;
        }

        // if percentage ends up at 100%, but there are some failing checks and it was rounded up, put 99% instead.
        if (percentage == 100 && passedHosts != allHosts) {
            percentage = 99;
        }

        return percentage;
    }


    return helper;
}]);
