import Vue from 'vue/dist/vue'

import { Line as LineChartGenerator } from 'vue-chartjs/legacy'
import {
    Chart as ChartJS,
    Title,
    Tooltip,
    Legend,
    LineElement,
    LinearScale,
    CategoryScale,
    PointElement
} from 'chart.js'
ChartJS.register(
    Title,
    Tooltip,
    Legend,
    LineElement,
    LinearScale,
    CategoryScale,
    PointElement
)
Vue.component('ChartAA', {
    template: `
      <LineChartGenerator
          :chart-options="chartOptions"
          :chart-data="chartData"
          :chart-id="chartId"
          :height="height"
      />
    `,
    components: { LineChartGenerator },
    props: {
        chartId: {
            type: String,
            default: 'line-chart'
        },
        height: {
            type: Number,
            default: 100
        },
        entity: {
            default: null,
            type: String
        },
        from: {
            default: null,
            type: String
        },
        to: {
            default: null,
            type: String
        },
        label: {
            default: '',
            type: String
        },
        color: {
            default: '',
            type: String
        }
    },
    data() {
        return {
            chartData: {
                labels: [''],
                datasets: [
                    {
                        label: this.label,
                        data: [4],
                        backgroundColor: this.color,
                    }
                ]
            },
            chartOptions: {
                responsive: true
            },
            methods: {
                setData : (x, y) => {
                    this.$data.chartData.labels = [...x]
                    this.$data.chartData.datasets[0].data = [...y]
                }
            },
        }
    },
    async mounted() {
        let chartFetch;
        const options = {
            method:
                'POST',
                headers: {
                'Content-Type': 'application/json'
            }
        }

        if (!this.$props.entity) {
            chartFetch = await fetch(`/admin/fr/chart/ga/visit`, {
                ...options,
                body: JSON.stringify({
                    from: this.$props.from,
                    to:  this.$props.to
                })
            })
            const chartData = await chartFetch.json()
            this.$data.methods.setData(chartData.x, chartData.y.Visites)
        } else {
            chartFetch = await fetch('/admin/fr/chart', {
                ...options,
                body: JSON.stringify({
                    entity: this.$props.entity,
                })
            })
            const chartData = await chartFetch.json()
            this.$data.methods.setData(chartData.x, chartData.y)
        }

    }
})
