<script setup lang="ts">

import useArchiveStore from "@/stores/archive";
import updater from "@/utils/updater";
import {IonButton, IonCard, IonCardContent, IonCardHeader, IonCardSubtitle, IonCardTitle} from "@ionic/vue";
import { onBeforeMount, ref } from "vue";

const emit = defineEmits<{(e:"back"):void, (e: "home"):void}>();
const archive = useArchiveStore();

const view = ref<number>(0);
const version = ref<string>("");
const logValue = ref<string>("");
const filesize = ref<number>(0);

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

async function flash() {
  view.value = 1;
  logValue.value = "Downloading file";
  await updater.obj.getFirmware( archive.getArchive[archive.getShownI]);
  logValue.value = "File recieved";
  filesize.value = updater.obj.getFileSize();
  logValue.value = "Starting to flash (0%)";
  await updater.obj.flashFirmware((message: string) => {
    logValue.value = message;
  }).catch((reason) => {
    logValue.value = reason;
  });
  // await updater.obj.flashFirmware();
  // logValue.value = "Flash complete!";
  view.value = 2;
}

function home() {
  emit("home");
}

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>FLASH</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>Disconnect</ion-button>-->
<!--      </div>-->
    </ion-card-header>

    <ion-card-content>
      <p>{{ version }} -> {{ archive.getArchive[archive.getShownI].title }}</p> <br>
      
      <!-- BEFORE FLASHING -->

      <ion-button @click="flash" v-if="view==0">Flash</ion-button>
      <ion-button @click="back" v-if="view==0">Cancel</ion-button>
    
      <!-- DURING FLASHING -->

      <p v-if="view!=0">Status info</p><br />
      <p v-if="view!=0"><strong>DO NOT CLOSE WHILE THE UPDATE IS RUNNING</strong></p><br />
      <p v-if="view!=0">Size: {{ filesize }}</p>
      <p v-if="view!=0">{{ logValue }}</p>
    
      <!-- AFTER FLASHING -->

      <ion-button @click="home" v-if="view==2">Finish</ion-button>

    </ion-card-content>
  </ion-card>
</template>

<style scoped>
.two-column {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
</style>