<template>
  <canvas id="policy-chart" />
</template>

<script setup>
import { onMounted, watch } from "vue";
import { usePStore } from "@/store/PolicyStore";
import { Chart } from "chart.js/auto";

const store = usePStore();

let chartHandle;

function buildChart() {
  const policy = store.getPolicy;
  const policy_labels = Array(policy.length)
    .fill(0)
    .map((_, i) => i);
  const RewardPlot = {
    data: {
      datasets: [
        {
          type: "line",
          xAxisID: "x",
          yAxisID: "y",
          data: policy,
          borderColor: "#3DC47A",
          borderWidth: 2,
          pointRadius: 0,
        },
      ],
    },
    options: {
      maintainAspectRatio: false,
      responsive: true,
      animation: {
        duration: 0,
      },
      plugins: {
        legend: {
          display: false,
        },
      },
      lineTension: 0,
      tooltip: {
        mode: "label",
      },
      scales: {
        x: {
          grid: {
            display: false,
          },
          labels: policy_labels,
          ticks: {
            autoSkip: true,
          },
        },
        y: {
          type: "linear",
          ticks: {
            beginAtZero: true,
          },
        },
      },
    },
  };
  const ctx = document.getElementById("policy-chart");
  // eslint-disable-next-line no-new
  chartHandle = new Chart(ctx, RewardPlot);
}

onMounted(() => {
  buildChart();
});

watch(
  () => store.getPolicy,
  () => {
    const policy = store.getPolicy;
    chartHandle.options.scales.x.labels = Array(policy.length)
      .fill(0)
      .map((_, i) => i);
    chartHandle.data.datasets[0].data = policy;

    chartHandle.update();
  }
);
</script>

<style scoped></style>
