<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();

let systemMemory = {};
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.memory.map(v => {
    return moment(v[1]*1000).format('hh:mm:ss');
  });

  const data = result.memory.map(v => {
    return v[0];
  });

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

onMounted(async () => {
  const [error, result] = await systemModel.memory();
  if (error) return console.error(error);
  systemMemory = result;

  await refresh();
});

</script>

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