<script setup>

import { ref, onMounted, onUnmounted } from 'vue';
import { Button, ProgressBar } from '@cloudron/pankow';
import { prettyDecimalSize, prettyDate } from '@cloudron/pankow/utils';
import { getColor } from '../utils.js';
import SystemModel from '../models/SystemModel.js';

const systemModel = SystemModel.create();

const props = defineProps({
  filesystem: Object
});

const isExpanded = ref(false);
const percent = ref(0);
const contents = ref([]); // cached
const speed = ref(-1); // cached
const ts = ref(0); // cached
const highlight = ref(null);
const showingCachedValue = ref(false);

let eventSource = null;

async function getUsage() {
  const [error, result] = await systemModel.filesystemUsage(props.filesystem.filesystem);
  if (error) return console.error(error);

  showingCachedValue.value = false;

  contents.value = [];

  eventSource = result;

  eventSource.addEventListener('message', function (message) {
      const payload = JSON.parse(message.data);

      if (payload.type === 'done') {
        percent.value = 100;
        ts.value = Date.now();

        contents.value.forEach((c, i) => c.color = getColor(contents.value.length, i));
        contents.value.sort((a, b) => b.usage - a.usage);

        const raw = localStorage.getItem('diskUsageCache');
        const cache = raw ? JSON.parse(raw) : {};
        cache[props.filesystem.filesystem] = { contents: contents.value, speed: speed.value, ts: ts.value };
        localStorage.setItem('diskUsageCache', JSON.stringify(cache));

        eventSource.close();
      } else if (payload.type === 'progress') {
        percent.value = payload.percent;
      } else {
        if (payload.speed) {
          speed.value = payload.speed;
        } else if (payload.content) {
          // this can happen if more than one backup sites for filesystem share the folder, so avoid negativ values here
          if (payload.content.usage < 0) payload.content.usage = 0;
          contents.value.push(payload.content);
        } else {
          console.error('Unkown data', payload);
        }
      }
  });

  eventSource.addEventListener('error', function (error) {
    console.log('error: errored', error);
    eventSource.close();
  });
}

async function onExpand() {
  if (isExpanded.value) return;

  isExpanded.value = true;

  getUsage();
}

function loadFromCache() {
  const raw = localStorage.getItem('diskUsageCache');
  const cache = raw ? JSON.parse(raw) : {};
  const entry = cache[props.filesystem.filesystem];

  if (!entry) return;

  if (Date.now() - entry.ts < 60 * 60 * 1000) { // 1 hour old
    contents.value = entry.contents;
    speed.value = entry.speed;
    percent.value = 100;
    ts.value = entry.ts;
    isExpanded.value = true;
    showingCachedValue.value = true;
  } else {
    delete cache[props.filesystem.filesystem]; // remove obsolete entry
    localStorage.setItem('diskUsageCache', JSON.stringify(cache));
  }
}

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

onUnmounted(() => {
  if (eventSource) eventSource.close();
});

</script>

<template>
  <div class="disk-item">
    <div class="disk-item-title">
      <div>{{ filesystem.mountpoint }} <small class="text-muted">{{ filesystem.type }}</small></div>
      <Button v-if="isExpanded" small tool plain icon="fa-solid fa-rotate" :disabled="percent < 100" :loading="percent < 100" @click="getUsage()"/>
    </div>
    <div class="disk-item-size-and-speed">
      <div>{{ prettyDecimalSize(filesystem.used) }} used of {{ prettyDecimalSize(filesystem.size) }} total
        <span v-if="showingCachedValue">(Last updated {{ prettyDate(ts) }})</span>
      </div>
      <div v-if="speed !== -1">I/O Rate: {{ prettyDecimalSize(speed * 1000 * 1000) }}/sec</div>
    </div>
    <div v-if="isExpanded" @mouseout="highlight = null">
      <ProgressBar v-if="percent < 100" mode="indeterminate" :show-label="false"/>
      <div v-else class="disk-size" style="overflow: visible;">
        <div class="disk-used" v-for="content in contents" :key="content.id" v-tooltip="content.name" @mouseover="highlight = content.id" :style="{ 'background-color': content.color, width: 100*content.usage/filesystem.size + '%' }" :class="{ highlight: highlight === content.id }"></div>
      </div>

      <div v-if="percent < 100" style="text-align: center; margin-top: 10px;">Calculating speed and disk usage ... {{ parseInt(percent) }}%</div>
      <div v-else>
        <table style="width: 100%;table-layout: fixed">
          <tr v-for="content in contents" :key="content.id" @mouseover="highlight = content.id" :class="{ highlight: highlight === content.id }">
            <td style="width: 20px"><div class="content-color-indicator" :style="{ backgroundColor: content.color }"></div></td>
            <td style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
              <a v-if="content.type === 'app'" :href="`/#/app/${content.id}/info`">{{ content.name }}</a>
              <a v-else-if="content.type === 'volume'" href="/#/volumes">{{ content.name }} (Volume)</a>
              <span v-else>{{ content.name }}</span>
            </td>
            <td style="text-align: right; white-space: nowrap;">{{ prettyDecimalSize(content.usage) }}</td>
          </tr>
        </table>
      </div>
    </div>
    <div v-else>
      <ProgressBar :value="parseInt(filesystem.capacity*100)" :show-label="false"/>
      <div style="text-align: center; margin-top: 10px;">
        <Button plain @click="onExpand()">Details</Button>
      </div>
    </div>
  </div>
</template>

<style scoped>

.disk-item {
  position: relative;
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  padding: 10px 16px;
  overflow: hidden;
  border-radius: 10px;
  background-color: var(--card-background);
  margin-bottom: 16px;
}

.disk-item:focus,
.disk-item:hover {
  box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
  background-color: var(--pankow-color-background-hover) !important;
  text-decoration: none;
}

.disk-item > div {
  margin: 6px 0;
}

.disk-item-title {
  display: flex;
  justify-content: space-between;
  font-weight: var(--pankow-font-weight-bold);
  font-size: 18px;
}

.disk-item-size-and-speed {
  display: flex;
  justify-content: space-between;
}

.disk-size {
  display: flex;
  position: relative;
  background-color: white;
  border-radius: var(--pankow-border-radius);
  height: 12px;
  overflow: hidden;
  margin-bottom: 12px;
}

.disk-used {
  display: inline-block;
  background-color: var(--pankow-color-primary);
  white-space: nowrap;
  height: 12px;
  min-width: 2px;
  transition: all 250ms;
}

.disk-used.highlight {
  transform: scaleY(2);
}

.content-legend-item {
  display: flex;
  align-items: center;
}

.content-color-indicator {
  height: 16px;
  width: 16px;
  border-radius: 4px;
}

.td {
  vertical-align: middle;
}

tr.highlight {
  font-weight: var(--pankow-font-weight-bold);
}

</style>
