<script>
import { Line, mixins } from 'vue-chartjs';

function resolve_data (set, keys) {
  const data = set[keys[0]];
  if (keys.length === 1)
    return data;
  return resolve_data (data, keys.slice (1));
}

export default {
  extends: Line,
  mixins:  [ mixins.reactiveData ],
  props:   {
    data: {
      type:     Array,
      required: true
    },
    xaxis: {
      type:     String,
      required: true
    },
    yaxis: {
      type:     Array,
      required: true
    }
  },
  computed: {
    chart_data () {
      const labels = this.data.map ((d) => d[this.xaxis]);
      const datasets = this.yaxis.map ((y, index) => {
        const res = {
          label:           y.label,
          data:            [],
          yAxisID:         index,
          borderColor:     y.color,
          backgroundColor: y.fill
        };
        for (const data of this.data)
          res.data.push (resolve_data (data, y.field.split ('/')));
        return res;
      });
      return { datasets, labels };
    },
    chart_options () {
      return {
        scales: {
          yAxes: this.yaxis.map (
            (y, index) => ({ id: index })
          )
        }
      };
    }
  },
  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>
