/**
 * @category    Webserver
 * @package     ATPX
 * @author      Sam Meredith <sam@aandtinstruments.com>
 * @version     0.1
 */

const chartOptionsMAWS =
{
    type: 'scatter',
    data:
    {
        datasets:
        [{
            label: 'MAWS',
            data: [],
            showLine: true,
            borderColor: 'rgb(255, 65, 54)',
            parsing: false,
            normalised: true
        },
        {
            label: 'Motion Corrected MAWS',
            data: [],
            showLine: true,
            borderColor: 'rgb(0, 116, 217)',
            parsing: false,
            normalised: true
        }]
    },
    options:
    {
        animation: false,
        datasets:
        {
            scatter:
            {
                pointRadius: 0
            }
        },
        maintainAspectRatio: false,
        parsing: false,
        plugins:
        {
            decimation:
            {
                enabled: true,
                algorithm: 'min-max'
            },
            legend:
            {
                display: true,
                position: 'bottom',
                labels:
                {
                    boxHeight: 1,
                    boxWidth: 20,
                    padding: 20
                },
            },
            title:
            { 
                display: true,
                font:
                {
                    size: 18
                },
                position: 'top',
                text: 'Measured Wind Speed Data'
            },
            tooltip:
            {
                enabled: false
            }
        },
        scales:
        {
            x:
            {
                type: 'realtime',
                realtime:
                {
                    duration: 60000,
                    delay: 300,
                    pause: false,
                    // Duration of data to be kept
                    // Undefined causes data to be deleted as soon as it falls off the chart
                    ttl: undefined,
                    // Frequency at which the chart is drawn
                    // Decreasing this has the biggest impact on CPU utilisation
                    frameRate: 10
                },
                ticks:
                {
                    display: false
                }
            },
            y:
            {
                // We want the max/min to be MAWS +/- 2kts, whatever MAWS might be
                suggestedMax: (scale) => (
                    Math.round(scale.chart.data.datasets[0].data.reduce((acc, curr) => {
                        return acc + curr.y / scale.chart.data.datasets[0].data.length;
                    }, 0) + 2)
                ),
                suggestedMin: (scale) => (
                    Math.round(scale.chart.data.datasets[0].data.reduce((acc, curr) => {
                        return acc + curr.y / scale.chart.data.datasets[0].data.length;
                    }, 0) - 2)
                ),
                title:
                {
                    display: true,
                    font:
                    {
                        size: 18
                    },
                    text: 'Wind Speed (kts)'
                }
            }
        },
        spanGaps: true
    }
};

const updateChartMAWS = function(chart, sender, instance)
{
    const fields = new Set(['0x1359', '0x0312']);

    const self = this;

    $.ajax(
    {
        type: 'POST',
        url: '/atp.fields.php',
        data: 
        {
            'action': 'getFields',
            'fields': Array.from(fields),
            'id': sender,
            'instance': instance
        },
        success: function(response) 
        {
            if (self.dataDebounce) return;

            // Parse value and append to dataset
            const json = JSON.parse(response);
        
            if (json.status)
            {
                let responseData = [];

                // Strip HTML tags
                const match = json.response.match(/.*<BODY>(.*)<\/BODY>.*/s);
                if (match)
                {
                    match[1].split("\r\n").forEach(datum =>
                    {
                        const split = datum.split('=');
                        responseData.push({ 'field' : parseInt(split[0]), 'data' : parseFloat(split[1]) });
                    });
                }
                
                const MAWSValue = (responseData.find(element => element.field == 0x1359) || { data: "NaN" }).data;

                chart.data.datasets[0].data.push(
                    {
                        x: Date.now(),
                        y: parseFloat(MAWSValue)
                    }
                );

                const MotionCorrectedMAWSValue = (responseData.find(element => element.field == 0x0312) || { data: "NaN" }).data;

                chart.data.datasets[1].data.push(
                    {
                        x: Date.now(),
                        y: parseFloat(MotionCorrectedMAWSValue)
                    }
                );

                // Update chart
                chart.update('quiet');
            }
        }
    });
}
