<template>
  <li>
    <span
      @click="toggleCollapse"
      class="file-manager-dir__label"
      :class="{ 'file-manager-dir__label--open': !isCollapsed }"
      >{{ dir.name }}/ <template v-if="isLoading">⟳</template></span>
    <ul v-if="content" v-show="!isCollapsed" class="file-manager-dir">
      <template
        v-for="file in content"
        :key="file.name"
      >
        <FileManagerDir
          v-if="file.type === 'directory'"
          :dir="file"
          @openFile="$emit('openFile', $event)" 
          @filePreview="$emit('filePreview', $event)"
        />
        <FileManagerFile
          v-else 
          :file="file"
          @openFile="$emit('openFile', $event)"
          @filePreview="$emit('filePreview', $event)"
        />
      </template>
    </ul>
  </li>
</template>
<script setup lang="ts">
import {inject, ref} from 'vue';
import FileManagerFile from './FileManagerFile.vue';
import FileManagerDir from './FileManagerDir.vue';
import {MountedFsSymbol} from '../../model/injectionSymbols';
import {VirtualDirectory, VirtualFile} from '../../model/FileSystem/types';

const fs = inject(MountedFsSymbol)!;
const isLoading = ref(false);
const isCollapsed = ref(true);

const emit = defineEmits<{
  'openFile': [value: VirtualFile]
  'filePreview': [value: VirtualFile]
}>();

const content = ref<(VirtualFile | VirtualDirectory)[]>([]);

const props = defineProps<{
  dir: VirtualDirectory;
}>();

async function toggleCollapse() {
  const isOpening = isCollapsed.value;
  isCollapsed.value = !isCollapsed.value;
  if (isOpening) {
    await fetchDirectoryContent();
  }
}

async function fetchDirectoryContent() {
  try {
    isLoading.value = true;
    // preload from cache
    content.value = await fs.listDir(props.dir, {cache: 'only-cache'});
    // replace with network
    content.value = await fs.listDir(props.dir, {cache: 'use-network'});
  } finally {
    isLoading.value = false;
  }
}

</script>
<style>

</style>