<template>
  <div>
    <!-- <p>{{tabPrices}}</p> -->
    <Line v-if="loaded"
      :chart-options="chartOptions"
      :chart-data="chartData"
      :chart-id="chartId"
      :plugins="plugins"
      :css-classes="cssClasses"
      :styles="styles"
      :width="width"
      :height="height"
    />
  </div>
</template>

<script>
import { Line } from 'vue-chartjs'
import {
  Chart as ChartJS,
  Title,
  Tooltip,
  Legend,
  LineElement,
  LinearScale,
  PointElement,
  CategoryScale
} from 'chart.js'
import constantesService from '@/services/constantes.service';
import i18nConstantes from "@/constantes/i18n.constantes.js";
import BigNumber from "bignumber.js";

ChartJS.register(Title, Tooltip, Legend, LineElement, LinearScale, PointElement,  CategoryScale)

export default {
  name: 'LineChart',
  components: { Line },
  props: {
    chartId: {
      type: String,
      default: 'line-chart'
    },
    width: {
      type: Number,
      default: 400
    },
    height: {
      type: Number,
      default: 400
    },
    cssClasses: {
      default: '',
      type: String
    },
    styles: {
      type: Object,
      default: () => {}
    },
    plugins: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      chartData: {
        labels: [ ],
        datasets: [
        {
          label: this.$t(i18nConstantes.bondingGraphGraphTitle),
          backgroundColor: '#3F43CD',
          data: []
        }
      ]
      },
      chartOptions: {
        responsive: true,
        maintainAspectRatio: false
      },
      tabPrices: undefined,
      loaded: false
    }
  },
  mounted() {
    try {
      fetch(constantesService.getConstanteNetwork("metadexPricesHistory"))
      .then(response => response.blob())
      .then(blob => {
        let reader = new FileReader()
        reader.onload = (e) => {
          try {
            this.tabPrices = JSON.parse(e.target.result);
            for (const price of this.tabPrices) {
              let d = new Date(price.createdAt);
              this.chartData.labels.push(d.toLocaleDateString());
              let n = new BigNumber(price.price);
              this.chartData.datasets[0].data.push(n.toFormat(3, 1));
            }
            this.loaded = true;
          } catch (error) {
            throw new Error("FETCH metadexPricesHistory error load datas => " + JSON.stringify(error));
          }
        }
        reader.readAsText(blob);
      })
      .catch(error => {
        throw new Error("FETCH metadexPricesHistory error => " + JSON.stringify(error));
      });
    } catch (error) {
      //console.log(error);
    }
    
  }
}
</script>