<template>
  <div class="home">
    <h1>
      Welcome to
      <em v-if="infoData?.name"> "{{ infoData.name }}" </em>
      <template v-else> UpEnd </template>
    </h1>
    <section class="latest" v-if="latestFiles">
      <h2>Most recently added files</h2>
      <ul>
        <li v-for="file in latestFiles" :key="file.hash">
          <div class="file-added">{{ file.added }}</div>
          <router-link
            :to="{ name: 'browse', params: { addresses: [file.hash] } }"
          >
            <div class="file-path">{{ file.path }}</div>
          </router-link>
        </li>
      </ul>
    </section>
  </div>
</template>

<script lang="ts">
import { IFile, VaultInfo } from "@/types/base";
import useSWRV from "swrv";
import { computed, defineComponent } from "vue";
import { fetcher } from "../utils";
import { formatRelative, parseISO } from "date-fns";

export default defineComponent({
  name: "Home",

  setup() {
    const { data: infoData } = useSWRV<VaultInfo, unknown>(
      "/api/info",
      fetcher
    );

    const { data: latestFilesRaw } = useSWRV<IFile[], unknown>(
      "/api/files/latest",
      fetcher
    );

    const latestFiles = computed(() => {
      if (latestFilesRaw?.value) {
        return latestFilesRaw.value.map((file) => {
          return {
            ...file,
            added: formatRelative(parseISO(file.added), new Date()),
            mtime: parseISO(file.added),
          };
        });
      }
    });

    return {
      infoData,
      latestFiles,
    };
  },
});
</script>

<style lang="scss">
h1 {
  text-align: center;
  font-weight: normal;
}

.latest {
  ul {
    list-style: none;
    padding: 0;
  }

  li {
    display: flex;

    & > * {
      margin: .1em .25em;
    }
  }

  .file-added {
    opacity: .77;
  }
}
</style>
