/*
* Copyright (c) 2021 Xilinx, Inc.
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
* associated documentation files (the "Software"), to deal in the Software without restriction, including 
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to 
* the following conditions: 
* 
* The above copyright notice and this permission notice shall be included in all copies or substantial 
* portions of the Software. 
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* 
*
*
*/
import { html, PolymerElement } from '@polymer/polymer/polymer-element.js';

class OverlayGraph extends PolymerElement {
    static get template() {
        return html`
        <style>
            :host {
                display: block;
            }
            canvas {
                width:100% !important;height:400px;box-shadow:0px 0px 4px 0px rgba(0,0,0,0.33);
            }
        </style>
        <div id=[[key]]><canvas></canvas></div>
    `;
    }

    ready() {
        super.ready();
    }

    _generateSplineGraph(refKey, data) {
        let self = this;
        const graphDiv = this.shadowRoot.querySelector('#' + refKey).querySelector('canvas');
        let ctx = graphDiv;
        document.querySelector("#pageloader").style.display = "none";
        self["chartoverlay" + refKey] = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: self._updateSeries(data)
            },
            options: {
                legend: {
                    position: 'bottom',
                    fontSize: 12,
                    fontFamily: 'Arial',
                },
                title: {
                    display: true,
                    text: 'Overlay'
                },
                tooltips: {
                    mode: 'index',
                    displayColors: true,
                    intersect: true
                },
                scales: {
                    xAxes: [{
                        type: 'time',
                        distribution: 'series',
                        ticks: {
                            source: 'labels'
                        },
                        time: {
                            displayFormats: {
                                quarter: 'YYYY-MM-DD HH:mm:ss'
                            }
                        },
                        gridLines: {
                            drawOnChartArea: false
                        }
                    }],
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        },
                        gridLines: {
                            drawOnChartArea: false
                        }
                    }]
                }
            }
        });
    }

    _updateSeries(data) {
        let seriesJson = [];
        let keys = [];
        let bkgcolor = ["#99bbff","#adebeb","#b3b300","#ffb3d9","#4dd2ff","#4d4dff","#5c8a8a","#cc33ff","#8585ad","#4da6ff","#ff00ff","#ff661a","#00cccc","#00b8e6","#9933ff","#00ace6","#6666ff","#75a3a3","#999966","#b35900","#99cc00","#ffaa00"];
        for (let i = 0; i < data.length; i++) {
            const allkey = Object.keys(data[i].data[0]);
            keys = _.filter(allkey, v => v != 'time');
        }
        for (let h = 0; h < keys.length; h++)
            seriesJson.push({'label' : keys[h],'fill': false,'backgroundColor': bkgcolor[h],'borderColor': bkgcolor[h],'pointBorderColor': bkgcolor[h],'pointBackgroundColor': bkgcolor[h],'pointHoverRadius': 5,'pointHoverBackgroundColor': "#ffffff",'pointHoverBorderColor':bkgcolor[h],'pointBorderWidth': 2, 'data': []});
        return seriesJson;
    }

    async _updatedUserGraph(data, refKey) {
        let self = this;
        if (self["chartoverlay" + refKey] != undefined) {
            for (let i = 0; i < data.length; i++) {
                const datum = data[i];
                let date = new Date(datum.data[i].time*1000);
                let xval = Date.parse(date);
                if(self["chartoverlay" + refKey].data.labels.length > 10){
                    self["chartoverlay" + refKey].data.labels.splice(0,1);
                }
                self["chartoverlay" + refKey].data.labels.push(xval);
                self["chartoverlay" + refKey].data.datasets.forEach((dataset) => {
                    let labval = [dataset.label];
                    if(dataset.data.length > 10){
                        dataset.data.splice(0,1);
                    }
                    dataset.data.push(parseInt(datum.data[0][labval], 16));
                });
            }
            self["chartoverlay" + refKey].update();
        }else if(data.length) {
            await self._generateSplineGraph(refKey, data);
        }
    }
}

window.customElements.define('overlay-graph', OverlayGraph);