<template>
  <div class="multi-data-widget-wrap h-100">
    <div class="row">
        <div class="offset-4 col-2"><strong>{{visualProperties.aggregate_func}}</strong></div>
      </div>
    <div class="container" v-for="(data, index) in visualProperties.data_point" :key="index">
      <div class="row align-items-center mt-3">
        <div class="col-4 data-point-text" :style="getTrendLineStyle(index)">{{data.title.text}}</div>
        <div class="col-2 data-point-text" :style="{ color: data.trend_line.color }">{{finalPoint[index]}} {{data.unit}}</div>
        <div class="col-6"><div data-sparkline="" :id="widgetId + data.uuid"></div></div>
      </div>
    </div>
  </div>
</template>

<script>
import Highcharts from 'highcharts'

export default {
  data () {
    return {
      widget: [],
      statusText: '',
      averagePoints: [],
      finalPoint: []
    }
  },
  props: {
    visualProperties: {
      type: Object,
      required: true
    },
    series: {
      type: Array,
      required: true
    },
    widgetId: {
      type: String,
      required: true
    },
    timezone: {
      type: String
    }
  },
  methods: {
    getTrendLineStyle (index) {
      let style = this.visualProperties.data_point[index].title.text_settings
      return {
        color: style.fontColor,
        fontSize: style.fontSize,
        textAlign: style.align,
        fontWeight: style.decorations.isBold ? 'bold' : '',
        fontStyle: style.decorations.isItalic ? 'italic' : '',
        textDecoration: style.decorations.isUnderline ? 'underline' : ''
      }
    },
    addDataPoint (point, index) {
      this.createAveragePoint(index, point[1])
      this.widget[index].series[0].addPoint(point, true, true)
    },
    resizeWidget (width, height) {
      setTimeout(() => {
        this.widget.setSize(width, height - 30)
      }, 10)
    },
    createAveragePoint (index, point) {
      if (this.visualProperties.aggregate_func === 'LIVE') {
        this.finalPoint.splice(index, 1, point)
      } else {
        if (this.averagePoints[index].length > 2) {
          if (this.averagePoints[index].length === 50) {
            this.averagePoints[index].shift()
          }
          this.averagePoints[index].push(point)
          if (this.visualProperties.aggregate_func === 'AVG') {
            const sum = this.averagePoints[index].reduce((a, b) => a + b, 0)
            const avg = (sum / this.averagePoints[index].length) || 0
            this.finalPoint.splice(index, 1, avg.toFixed(2))
          } else if (this.visualProperties.aggregate_func === 'MIN') {
            let min = Math.min.apply(Math, this.averagePoints[index])
            this.finalPoint.splice(index, 1, min.toFixed(2))
          } else if (this.visualProperties.aggregate_func === 'MAX') {
            let max = Math.max.apply(Math, this.averagePoints[index])
            this.finalPoint.splice(index, 1, max.toFixed(2))
          }
        } else {
          this.averagePoints[index].push(point)
          this.finalPoint.splice(index, 1, point)
        }
      }
    },
    createChartConfig () {
      Highcharts.SparkLine = function (a, b, c) {
        const hasRenderToArg = typeof a === 'string' || a.nodeName
        let options = arguments[hasRenderToArg ? 1 : 0]
        const defaultOptions = {
          chart: {
            renderTo: (options.chart && options.chart.renderTo) || (hasRenderToArg && a),
            backgroundColor: '',
            borderRadius: 6,
            borderWidth: 0,
            type: 'spline',
            margin: [15, 25, 15, 25],
            height: 50,
            styleMode: true,
            style: {
              overflow: 'visible'
            },
            skipClone: true
          },
          title: {
            text: ''
          },
          credits: {
            enabled: false
          },
          xAxis: {
            labels: {
              enabled: false
            },
            title: {
              text: null
            },
            visible: false,
            startOnTick: false,
            endOnTick: false,
            tickPositions: []
          },
          yAxis: {
            visible: false,
            endOnTick: false,
            startOnTick: false,
            labels: {
              enabled: false
            },
            title: {
              text: null
            },
            tickPositions: [0]
          },
          legend: {
            enabled: false
          },
          tooltip: {
            hideDelay: 0,
            outside: true,
            shared: true
          },
          plotOptions: {
            series: {
              animation: false,
              lineWidth: 1,
              shadow: false,
              states: {
                hover: {
                  lineWidth: 1
                }
              },
              marker: {
                radius: 1,
                enabled: false,
                states: {
                  hover: {
                    radius: 2
                  }
                }
              },
              fillOpacity: 0.25
            },
            column: {
              negativeColor: '#910000',
              borderColor: 'silver'
            }
          }
        }

        options = Highcharts.merge(defaultOptions, options)
        return hasRenderToArg ? new Highcharts.Chart(a, options, c) : new Highcharts.Chart(options, b)
      }
    },
    updateSeriesData (data, index) {
      this.widget.series[index].update({
        data: data
      }, true)
    },
    doChunk () {
      const ids = this.visualProperties.data_point.map(i => i.uuid)
      const tds = []
      ids.forEach(i => {
        if (i) { tds.push(document.getElementById(this.widgetId + i)) }
      })

      // eslint-disable-next-line no-unused-vars
      let n = 0
      const time = +new Date()
      const len = tds.length
      let widgets = []
      for (let i = 0; i < len; i += 1) {
        const td = tds[i]
        const stringdata = td.dataset.sparkline
        const arr = stringdata.split('; ')
        const chart = {
          type: 'spline',
          backgroundColor: this.visualProperties.data_point[i] ? this.visualProperties.data_point[i].trend_line.background_color : 'none'
        }

        if (arr[1]) {
          chart.type = arr[1]
        }

        widgets.push(Highcharts.SparkLine(td, {
          series: [{
            data: [0, 0, 0, 0, 0],
            pointStart: 1
          }],
          tooltip: {
            enabled: true,
            headerFormat: '<span style="font-size: 10px">' + this.visualProperties.data_point[i].title.text + '</span><br/>',
            pointFormat: '<b>{point.y}</b> ' + this.visualProperties.data_point[i].unit
          },
          chart: chart,
          plotOptions: {
            series: {
              dashStyle: this.visualProperties.data_point[i] ? this.visualProperties.data_point[i].trend_line.line_type : 'Solid',
              lineWidth: this.visualProperties.data_point[i] ? this.visualProperties.data_point[i].trend_line.line_width : 1,
              color: this.visualProperties.data_point[i] ? this.visualProperties.data_point[i].trend_line.color : 'black'
            }
          }
        })
        )
        this.averagePoints.push([0])

        n += 1

        if (new Date() - time > 500) {
          tds.splice(0, i + 1)
          setTimeout(this.doChunk(), 0)
          break
        }
      }
      this.widget = widgets
    }
  },
  mounted () {
    this.createChartConfig()
    this.doChunk()
  }
}
</script>

<style lang="scss" scoped>
  .multi-data-widget-wrap {
    .data-point-text {
      font-size: 20px;
    }
  }
</style>
