<script setup>

import { ref, onUnmounted } from 'vue';
import { Button } from '@cloudron/pankow';
import { prettyDecimalSize } from '@cloudron/pankow/utils';
import AppsModel from '../models/AppsModel.js';
import VolumesModel from '../models/VolumesModel.js';
import SystemModel from '../models/SystemModel.js';

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

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

// https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array
function shuffle(a) {
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

function hue(numOfSteps, step) {
  const deg = 360/numOfSteps;
  return `hsl(${deg*step} 70% 50%)`;
}

let colorIndex = 0;
let colors = [];
function resetColors(n) {
  colorIndex = 7;
  colors = [];
  for (let i = 0; i < n; i++) colors.push(hue(n, i));
}

function getNextColor() {
  return colors[colorIndex++];
}

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

let eventSource = null;

async function refresh() {
  let [error, result] = await appsModel.list();
  if (error) return console.error(error);

  const appsById = {};
  result.forEach(a => { appsById[a.id] = a; });

  [error, result] = await volumesModel.list();
  if (error) return console.error(error);

  const volumesById = {};
  result.forEach(v => { volumesById[v.id] = v; });

  [error, result] = await systemModel.filesystemUsage(props.filesystem.filesystem);
  if (error) return console.error(error);

  contents.value = [];

  eventSource = result;

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

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

        // we first 8 colors are reserved for known system contents
        resetColors(contents.value.length + 8);
        contents.value.forEach(content => {
          // assign fixed colors for known entries
          if (content.id === 'platformdata') content.color = colors[0];
          else if (content.id === 'boxdata') content.color = colors[1];
          else if (content.id === 'maildata') content.color = colors[2];
          else if (content.id === 'cloudron-backup-default') content.color = colors[3];
          else if (content.id === 'docker') content.color = colors[4];
          else if (content.id === 'docker-volumes') content.color = colors[5];
          else if (content.id === '/apps.swap') content.color = colors[6];
          else if (content.id === 'os') content.color = colors[7];
          else content.color = getNextColor();
        });
        contents.value.sort((a, b) => b.usage - a.usage);

        eventSource.close();
      } else if (payload.type === 'progress') {
        percent.value = payload.percent;
      } else {
        if (payload.speed) {
          speed.value = payload.speed;
        } else if (payload.content) {
          if (payload.content.type === 'app') {
            payload.content.app = appsById[payload.content.id];
            if (!payload.content.app) payload.content.uninstalled = true;
            else payload.content.label = payload.content.app.label || payload.content.app.fqdn;
          } else if (payload.content.type === 'volume') {
            payload.content.volume = volumesById[payload.content.id];
            payload.content.label = payload.content.volume ? `Volume ${payload.content.volume.name}` : 'Removed volume';
          } else {
            payload.content.label = payload.content.id;
          }
          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;

  refresh();
}

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

</script>

<template>
  <div class="disk-item">
    <div class="disk-item-title">{{ filesystem.mountpoint }} <Button v-if="isExpanded" small tool plain icon="fa-solid fa-rotate" :disabled="percent < 100" :loading="percent < 100" @click="refresh()"/></div>
    <div class="disk-item-type-and-speed">{{ filesystem.type }} <span v-if="speed !== -1">{{ prettyDecimalSize(speed * 1000 * 1000) }}/sec</span></div>
    <div class="usage-label">
      <div>{{ prettyDecimalSize(filesystem.size) }} total</div>
      <div>{{ prettyDecimalSize(filesystem.available) }} available</div>
    </div>
    <div v-if="isExpanded" @mouseout="highlight = null">
      <div class="disk-size" v-if="percent < 100">
        <div class="disk-used disk-used-busy"></div>
      </div>
      <div class="disk-size" style="overflow: visible;" v-else>
        <div class="disk-used" v-for="content in contents" :key="content.id" v-tooltip="content.id" @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;">Calculating speed and disk usage ... {{ percent }}%</div>
      <div v-else>
        <table style="width: 100%">
          <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>{{ content.label }}</td>
            <td style="text-align: right">{{ prettyDecimalSize(content.usage) }}</td>
          </tr>
        </table>
      </div>
    </div>
    <div v-else>
      <div class="disk-size">
        <div class="disk-used" :style="{ width: parseInt(filesystem.capacity*100) + '%' }"></div>
      </div>
      <div style="text-align: center">
        <Button plain @click="onExpand()">Details</Button>
      </div>
    </div>
  </div>
</template>

<style scoped>

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

.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: bold;
  font-size: 18px;
}

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

.usage-label {
  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);
}

.disk-used-busy {
  min-width: 0;
}

.disk-used-busy::after {
  content: '';
  width: 90%;
  height: 100%;
  background: var(--pankow-color-primary);
  position: absolute;
  top: 0;
  left: 0;
  box-sizing: border-box;
  animation: pankow-progress-bar-indeterminate-animation 1.5s ease-in-out infinite;
  border-radius: calc(var(--pankow-border-radius) / 1.5);
}

.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: bold;
}

</style>
