<script setup>

import { useI18n } from 'vue-i18n';
const i18n = useI18n();
const t = i18n.t;

import { ref, onMounted, useTemplateRef, nextTick, onUnmounted } from 'vue';
import AppsModel from '../../models/AppsModel.js';
import { prettyBinarySize, prettyDecimalSize } from 'pankow/utils';
import SystemModel from '../../models/SystemModel.js';
import { SingleSelect } from 'pankow';
import GraphItem from '../GraphItem.vue';

const { app } = defineProps([ 'app' ]);

const appsModel = AppsModel.create();
const systemModel = SystemModel.create();

const periods = [
  { hours: 0,     label: t('app.graphs.period.live'), format: 'hh:mm A', tooltipFormat: 'hh:mm:ss A' },
  { hours: 1,     label: t('app.graphs.period.1h'), format: 'hh:mm A', tooltipFormat: 'hh:mm:ss A' },
  { hours: 6,     label: t('app.graphs.period.6h'), format: 'hh:mm A', tooltipFormat: 'hh:mm A' },
  { hours: 12,    label: t('app.graphs.period.12h'), format: 'hh:mm A', tooltipFormat: 'hh:mm A' },
  { hours: 24,    label: t('app.graphs.period.24h'), format: 'hh:mm A', tooltipFormat: 'hh:mm A' },
  { hours: 24*7,  label: t('app.graphs.period.7d'), format: 'DD MMM', tooltipFormat: 'DD MMM hh:mm A' },
  { hours: 24*30, label: t('app.graphs.period.30d'), format: 'DD MMM', tooltipFormat: 'DD MMM hh:mm A' },
];

const busy = ref(true);
const period = ref(periods[0]);
const cpuGraphItem = useTemplateRef('cpuGraphItem');
const memoryGraphItem = useTemplateRef('memoryGraphItem');
const diskGraphItem = useTemplateRef('diskGraphItem');
const networkGraphItem = useTemplateRef('networkGraphItem');

const networkReadTotal = ref(0);
const networkWriteTotal = ref(0);

const blockReadTotal = ref(0);
const blockWriteTotal = ref(0);

const appMemory = app.memoryLimit || app.manifest.memoryLimit || 256*1024*1024;
let systemCpus = {};
let metricStream = null;

async function liveRefresh() {
  metricStream = await appsModel.getMetricStream(app.id);
  metricStream.onerror = (error) => console.log('event stream error:', error);
  metricStream.onmessage = (message) => {
    const data = JSON.parse(message.data);

    cpuGraphItem.value.pushData(data.cpu);
    memoryGraphItem.value.pushData(data.memory);
    diskGraphItem.value.pushData(data.blockReadRate, data.blockWriteRate);
    networkGraphItem.value.pushData(data.networkReadRate, data.networkWriteRate);

    blockReadTotal.value = prettyDecimalSize(data.blockReadTotal);
    blockWriteTotal.value = prettyDecimalSize(data.blockWriteTotal);
    networkReadTotal.value = prettyDecimalSize(data.networkReadTotal);
    networkWriteTotal.value = prettyDecimalSize(data.networkWriteTotal);
  };
}

async function onPeriodChange() {
  if (metricStream) {
    metricStream.close();
    metricStream = null;
  }

  if (period.value.hours === 0) return await liveRefresh();

  const [error, metrics] = await appsModel.getMetrics(app.id, { fromSecs: period.value.hours * 60 * 60, intervalSecs: 300 });
  if (error) return console.error(error);

  cpuGraphItem.value.setData(metrics.cpu);
  memoryGraphItem.value.setData(metrics.memory);
  diskGraphItem.value.setData(metrics.blockReadRate, metrics.blockWriteRate);
  networkGraphItem.value.setData(metrics.networkReadRate, metrics.networkWriteRate);

  networkReadTotal.value = prettyDecimalSize(metrics.networkReadTotal);
  networkWriteTotal.value = prettyDecimalSize(metrics.networkWriteTotal);
  blockReadTotal.value = prettyDecimalSize(metrics.blockReadTotal);
  blockWriteTotal.value = prettyDecimalSize(metrics.blockWriteTotal);
}

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

  systemCpus = result;

  busy.value = false;
  await nextTick();

  await onPeriodChange();
});

onUnmounted(async () => {
  if (metricStream) metricStream.close();
});

</script>

<template>
    <div class="graphs" v-if="!busy">
      <div style="text-align: right"><SingleSelect @select="onPeriodChange()" v-model="period" :options="periods" option-label="label"/></div>

      <GraphItem ref="cpuGraphItem"
        :title="$t('system.cpuUsage.title')"
        :subtext="`${app.cpuQuota}% of ${systemCpus.length} Core ${systemCpus[0].model}`"
        :period="period"
        yscale="cpu"
        :dataset-labels="['CPU']"
        :dataset-colors="['#9ad0f5']"
        :cpu-count="systemCpus.length"
        :high-mark="systemCpus.length * app.cpuQuota/100"
        >
      </GraphItem>

      <GraphItem ref="memoryGraphItem"
        title="Memory"
        :subtext="`RAM: ${prettyBinarySize(app.memoryLimit || app.manifest.memoryLimit || 256*1024*1024)}`"
        :period="period"
        yscale="memory"
        :dataset-labels="['Memory']"
        :dataset-colors="['#9ad0f5']"
        :memory="appMemory"
        :high-mark="appMemory"
        >
      </GraphItem>

      <GraphItem ref="diskGraphItem"
        title="Disk I/O"
        :subtext="$t('app.graphs.diskIOTotal', { read: blockReadTotal, write: blockWriteTotal })"
        :period="period"
        yscale="disk"
        :dataset-labels="['Read', 'Write']"
        :dataset-colors="['#9ad0f5', '#ffb1c1']"
        >
      </GraphItem>

      <GraphItem ref="networkGraphItem"
        title="Network I/O"
        :subtext="$t('app.graphs.networkIOTotal', { inbound: networkReadTotal, outbound: networkWriteTotal })"
        :period="period"
        yscale="network"
        :dataset-labels="['RX', 'TX']"
        :dataset-colors="['#9ad0f5', '#ffb1c1']"
        >
      </GraphItem>
    </div>
</template>
