<script setup lang="ts">
import useArchiveStore from "@/stores/archive";
import { versionNotes } from "@/utils/types";
import updater from "@/utils/updater";
import {
  IonButton,
  IonCard,
  IonCardContent,
  IonCardHeader,
  IonCardSubtitle,
  IonCardTitle,
  IonIcon,
  IonNote,
IonLabel, IonItem,
    IonList
} from "@ionic/vue";
import {chevronForward} from "ionicons/icons";
import { onBeforeMount, ref, watch } from "vue";

const archive = useArchiveStore();
const emit = defineEmits<{(e: "back"): void, (e: "disconnect"): void, (e: "details"):void}>();
const versions = ref<versionNotes[]>([]);
const version = ref<string>("");

const back = () => {
  emit("back");
}

const disconnect = () => {
  emit("disconnect");
};

const details = (index: number) => {
  archive.setShownI(index);
  emit("details");
}

watch(() => archive.getArchive, (newValue) => versions.value = newValue, {immediate: true});

onBeforeMount(async () => {
  version.value = await updater.obj.getBoardVersion();
});
</script>

<template>
  <ion-card>
    <ion-card-header class="two-column">
      <div class="header-column">
        <ion-card-title>ARCHIVE</ion-card-title>
        <ion-card-title>Board</ion-card-title>
        <ion-card-subtitle>{{ version }}</ion-card-subtitle>
      </div>
      <div style="flex-grow: 1"></div>
      <div>
        <ion-button @click="disconnect">Disconnect</ion-button>
      </div>
    </ion-card-header>

    <ion-card-content>
      <ion-button @click="back">Back</ion-button>
      <ion-list lines="full" class="item-scroll">
        <ion-item :button="true" v-for="(version, index) in versions" :key="index" @click="details(index)">
          <ion-label>
            <strong>{{version.title}}</strong> <br>
            <ion-note>{{ version.date }}</ion-note>
          </ion-label>
          <div slot="end" class="metadata-end-wrapper">
            <ion-icon color="medium" :icon="chevronForward"></ion-icon>
          </div>
        </ion-item>
      </ion-list>
    </ion-card-content>
  </ion-card>
</template>

<style scoped>
.two-column {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.item-scroll {
  max-height: 200px;
  overflow: scroll;
}
.metadata-end-wrapper {
  position: absolute;

  top: 10px;
  inset-inline-end: 10px;

  font-size: 0.8rem;

  display: flex;
  align-items: center;
}
</style>