<script lang="ts">
import { ref } from "vue";
import { invoke } from "@tauri-apps/api/tauri";
import { Line } from 'vue-chartjs';
import { Chart as ChartJS, Title, Tooltip, Legend, LineElement, CategoryScale, LinearScale, PointElement } from 'chart.js';

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

export default {
  name: 'LineChart',
  components: { Line },
  setup() {
    const chartData = ref({
      datasets: [{ // Ensure datasets is an array
        label: 'My Dataset', // Add a label for the dataset
        data: [], // Initial data
        fill: false, // Set to true if you want the area under the line to be filled
        borderColor: 'blue', // Set the line color
        tension: 0.1 // Adjust the tension for smoothness
      }]
    });

    const chartOptions = {
      responsive: true,
      scales: {
        y: {
          min: 0,
          max: 100
        },
        x: {
          ticks: {
            callback: (value, index, values) => {
              // Show only 5 timestamps on the x-axis
              const step = Math.floor(values.length / 5);
              return index % step === 0 ? chartData.value.labels[index] : ''; // Show the label only for selected indices
            }
          }
        }
      }
    };

    const updateData = async () => {
      const my_data = await invoke("random_data");

      const values = my_data.map((point: { value: number }) => point.value);
      const timestamps = my_data.map((point: { timestamp: string }) => point.timestamp);

      chartData.value = {
        labels: timestamps,
        datasets: [{
          label: 'My Dataset', // Add a label for the dataset
          data: values, // Access the data property
          fill: false, // Set to true if you want the area under the line to be filled
          borderColor: 'green', // Set the line color
          tension: 0.1 // Adjust the tension for smoothness
        }]
      };
    };

    return {
      chartData,
      chartOptions,
      updateData
    };
  }
}
</script>

<template>
  <Line id="my-chart-id" :options="chartOptions" :data="chartData" />
  <button @click="updateData">Click me</button>
</template>

