/*
* 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 "../../../../node_modules/@polymer/polymer/polymer-element.js";
import { configObj } from "../../../shared/constants.js";

class UserGraph 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) {
    const graphDiv = this.shadowRoot.querySelector('#' + refKey).querySelector('canvas');
    let ctx = graphDiv;
    let self = this;
    document.querySelector("#pageloader").style.display = "none";
    self["chartplot" + refKey] = new Chart(ctx, {
      type: 'line',
      data: {
        labels: [],
        datasets: [{
          label: configObj[self.key]['legend'],
          fill: false,
          data: [],
          backgroundColor: ['#99bbff'],
          borderColor: ['#99bbff'],
          pointBorderColor: "#99bbff",
          pointBackgroundColor: "#99bbff",
          pointHoverRadius: 5,
          pointHoverBackgroundColor: "#ffffff",
          pointHoverBorderColor: "#99bbff",
          pointBorderWidth: 2
        }]
      },
      options: {
        legend: {
          position: 'bottom',
          fontSize: 12,
          fontFamily: 'Arial'
        },
        title: {
          display: true,
          text: configObj[self.key]['title']
        },
        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
            }
          }]
        }
      }
    });
  }

  async _updatedUserGraph(graphdata, refKey) {
    let self = this;
    let isgraphupdated = false;

    if (self["chartplot" + refKey] != undefined) {
      const title = configObj[self.key]['title'];
      self["chartplot" + refKey].options.title.text = title;

      if (graphdata.length > 0) {
        for (let i = 0; i < graphdata.length; i++) {
          const datum = graphdata[i];
          let date = new Date(datum.data[i].time * 1000);
          let xval = Date.parse(date);

          if (self["chartplot" + refKey].data.labels.length > 10) {
            self["chartplot" + refKey].data.labels.splice(0, 1);
          }

          if (self["chartplot" + refKey].data.labels.indexOf(xval) == -1) {
            self["chartplot" + refKey].data.labels.push(xval);
            self["chartplot" + refKey].data.datasets.forEach(dataset => {
              if (dataset.data.length > 10) {
                dataset.data.splice(0, 1);
              }

              dataset.data.push(parseInt(datum.data[0][configObj[self.key].legend], 16));
            });
            isgraphupdated = true;
          }
        }

        if (isgraphupdated) self["chartplot" + refKey].update();
      }
    } else if (graphdata.length) {
      await self._generateSplineGraph(refKey);
    }
  }

}

window.customElements.define('user-graph', UserGraph);