<script>
import { Line, mixins } from 'vue-chartjs';
import { resolve_data } from '../helper';

export default {
  extends: Line,
  mixins:  [ mixins.reactiveData ],
  props:   {
    data: {
      type:     Array,
      required: true
    },
    xaxis: {
      type:     String,
      required: true
    },
    yaxis: {
      type:     Array,
      required: true
    },
    remove_duplicates: {
      type:    Boolean,
      default: false
    }
  },
  computed: {
    chart_data () {
      const labels = this.data.map ((d) => resolve_data (d, this.xaxis));
      const datasets = this.yaxis.map ((y, index) => {
        const res = {
          label:           y.label,
          data:            [],
          yAxisID:         index,
          borderColor:     y.color,
          backgroundColor: y.fill,
          spanGaps:        true
        };
        let last = null;
        for (let i = 0; i < this.data.length; i++) {
          const data = this.data[i];
          const val = resolve_data (data, y.field);
          if (
            !this.remove_duplicates
            || last !== val
            || this.data.length - 1 === i
          )
            res.data.push (val);
          else
            res.data.push (null);
          last = val;
        }
        return res;
      });
      return { datasets, labels };
    },
    chart_options () {
      return {
        animation:                   { duration: 0 },
        responsiveAnimationDuration: 0,
        scales:                      {
          yAxes:                       this.yaxis.map (
            (y, index) => {
              const range = {};
              if (typeof y.min_value === 'number')
                range.suggestedMin = y.min_value;
              if (typeof y.max_value === 'number')
                range.suggestedMax = y.max_value;

              return {
                id:         index,
                ticks:      range,
                scaleLabel: {
                  labelString: y.label,
                  display:     true,
                  lineHeight:  1,
                  padding:     0.1
                }
              };
            }
          )
        }
      };
    }
  },
  watch: {
    chart_data () {
      // eslint-disable-next-line no-underscore-dangle
      this.renderChart (this.chart_data, this.chart_options);
    }
  },
  mounted () {
    this.renderChart (this.chart_data, this.chart_options);
  }
};
</script>

<style>
</style>
