<?php
require_once(dirname(__FILE__) . '/../dashlet-helper.inc.php');

dashlets_data_check();

service_health_dashlet();

function service_health_dashlet() {

    $id = 'service_health_' . random_string(6);

    $categories = '';
    $ok = '';
    $warning = '';
    $critical = '';
    $unknown = '';
    $problems = '';
    $unhandled = '';
    $alive = array();
    $pos = 0;

    $servers = get_servers();
    foreach ($servers as $server) {

        // We currently have nothing to show here for NLS or NNA, so don't show it
        if (in_array($server['server_type'], array(SERVER_TYPE_NLS, SERVER_TYPE_NNA))) {
            continue;
        }

        $data = get_server_data($server);
        if (service_health_check_server_alive($server, $server_name, $server_type, $img, $msg, $ok) == false)
            $alive[] = $pos;
        $pos++;
        if (!$data)
            continue;
        
        $categories .= json_encode($server['name']) . ',';

        $ok .= $data['services_ok'] . ',';
        $warning .= $data['services_warning'] . ',';
        $critical .= $data['services_critical'] . ',';
        $unknown .= $data['services_unknown'] . ',';
        $problems .= $data['services_problems'] . ',';
        $unhandled .= $data['services_problems_unhandled'] . ',';
    }

    $categories = rtrim($categories, ',');
    $ok = rtrim($ok, ',');
    $warning = rtrim($warning, ',');
    $critical = rtrim($critical, ',');
    $unknown = rtrim($unknown, ',');
    $problems = rtrim($problems, ',');
    $unhandled = rtrim($unhandled, ',');

    ?>
        <div id="<?php echo $id; ?>" style="width: 100%; height: 100%">
        </div>
        <script type="text/javascript">

        $(function () {

            function get_<?php echo $id; ?>_content() {
                var bodyStyles = window.getComputedStyle(document.body);
                const textColor = bodyStyles.getPropertyValue('color');
                const backgroundColor = bodyStyles.getPropertyValue('background-color');

                Highcharts.setOptions({
                    colors: [ '#b2ff5f', '#FEFF5F', '#FF795F', '#FFC45F', '#FFE4AF', '#ff4c00' ]
                });

                var chart = new Highcharts.Chart({
                    chart: {
                        events: {
                            load: function() {
                                // for each dead server change the color in the series to corresponding greyscale
                                deadServers = <?php echo json_encode($alive); ?>;
                                greyscale = ['#b1d788', '#d7d788', '#d79588', '#d7bA88', '#eaddc1', '#bf663f' ];
                                this.series.forEach((s, si=0) => {
                                    deadServers.forEach((serv) => {
                                        try{
                                            s.points[serv].update({
                                                color: greyscale[si]
                                            });
                                            // this must be kept in as long as Highcharts version is 4.1.9 (not updated)
                                            s.points[serv].setState('hover');
                                            s.points[serv].setState();
                                        } catch (TypeError) {
                                            //if servers are dead long enough they lose data and become null, catch if this occurs
                                        }
                                        
                                    });
                                });
                            }
                        },
                        renderTo: '<?php echo $id; ?>',
                        type: 'column',
                        backgroundColor: backgroundColor,
                    },
                    credits: {
                        enabled: false
                    },
                    title: {
                        text: '<?php echo _('Service Health Summary by Nagios Server'); ?>',
                        style: {
                            color: textColor
                        }
                    },
                    xAxis: {
                        categories: [<?php echo $categories; ?>],
                        labels: {
                            formatter () {
                                return `<span style="color: `+ textColor +`">${this.value}</span>`
                            }
                        }
                    },
                    yAxis: {
                        allowDecimals: false,
                        min: 0,
                        
                        title: {
                            text: '<?php echo _('Counts by state'); ?>',
                            style: {
                                color: textColor
                            }
                        },
                        
                        labels: {
                            formatter () {
                                return `<span style="color: `+ textColor +`">${this.value}</span>`
                            }
                        }
                    },
                    tooltip: {
                        formatter: function() {
                            return '<b>' + this.x + '</b><br/>'+
                                this.series.name +': '+ this.y +'<br/>'+
                                '<?php echo _('Total'); ?>: '+ this.point.stackTotal;
                        }
                    },
                    plotOptions: {
                        column: {
                            stacking: 'normal'
                        }
                    },
                    legend: {
                        itemStyle: {
                            font: '9pt Trebuchet MS, Verdana, sans-serif',
                            color: textColor

                        },
                        itemHoverStyle: {
                            color: '#b8b9ba'
                        },
                        itemHiddenStyle: {
                            color: 'gray'
                        }
                    }, 
                    series: [
            			{
            	            name: '<?php echo _('Ok'); ?>',
            	            data: [<?php echo $ok; ?>],
            	            stack: 'state',
            	        },
            	        {
            	            name: '<?php echo _('Warning'); ?>',
            	            data: [<?php echo $warning; ?>],
            	            stack: 'state'
            	        },
            	        {
            	            name: '<?php echo _('Critical'); ?>',
            	            data: [<?php echo $critical; ?>],
            	            stack: 'state'
            	        },
                        {
                            name: '<?php echo _('Unknown'); ?>',
                            data: [<?php echo $unknown; ?>],
                            stack: 'state'
                        },
            	        {
            	            name: '<?php echo _('Problems'); ?>',
            	            data: [<?php echo $problems; ?>],
            	            stack: 'pseudo'
            	        },
            	        {
            	            name: '<?php echo _('Unhandled'); ?>',
            	            data: [<?php echo $unhandled; ?>],
            	            stack: 'pseudo'
            	        }
                    ],
                    exporting: {
                        chartOptions: {
                            chart: {
                                // background color must be set to be non-transparent for non-png exports
                                backgroundColor: backgroundColor
                            }
                        },
                        enabled: true,
                        buttons: {
                            contextButton: {
                                symbolStroke: textColor,
                                theme: {
                                    fill: backgroundColor,
                                    stroke: backgroundColor,
                                }
                            }
                        }
                    }
                });
            }
            
            $('#<?php echo $id; ?>').closest('.ui-resizable').on('resizestop', function() {
                get_<?php echo $id; ?>_content();
            });

            get_<?php echo $id; ?>_content();
        }); 
        </script>
    <?php
}


function service_health_check_server_alive($server, &$server_name, &$server_type, &$img, &$msg, &$ok = null) {

    $server = get_server($server);
    if ($server === false)
        return false;

    $server_name = encode_html($server['name']);
    $server_type = server_type_to_readable($server['server_type']);

    if (check_server_authentication($server, $failure_on_stale = true) === false) {
        return false;
    }

    return true;

}
