<script setup>

import { ref, onMounted, useTemplateRef } from 'vue';
import Chart from 'chart.js/auto';
import moment from 'moment-timezone';
import Section from './Section.vue';
import SystemModel from '../models/SystemModel.js';

const systemModel = SystemModel.create();

const graph = useTemplateRef('graph');
const period = ref(6);

async function refresh() {
  const [error, result] = await systemModel.graphs(period.value * 60);
  if (error) return console.error(error);

  const labels = result.cpu.map(v => {
    return moment(v[1]*1000).format('hh:mm:ss');
  });

  const data = result.cpu.map(v => {
    // v[0] is in percent, need to scale up depending on cpu count 2 cpus => 200% max
    return parseInt(v[0]);
  });

  new Chart(graph.value, {
    type: 'line',
    data: {
      labels,
      datasets: [{
        label: 'CPU',
        data: data,
        radius: 0,
        borderWidth: 1,
        tension: 0.4,
      }]
    },
    options: {
      plugins: {
        legend: false
      },
      scales: {
        y: {
          min: 0,
          max: result.cpuCount*100
        }
      },
      interaction: {
        intersect: false,
        mode: 'nearest',
        axis: 'x'
      }
    }
  });
}

onMounted(async () => {
  await refresh();
});

</script>

<template>
  <Section :title="$t('system.cpuUsage.title')">
    <div style="position: relative; width: 100%; height: 200px;"><canvas ref="graph"></canvas></div>
  </Section>
</template>
