<template>
  <div class="flex flex-col h-fit w-full border border-primary rounded-md">
    <div class="bg-primary p-2 text-white flex flex-row justify-between items-center">
      <p>{{ backup }}</p>
      <div class="flex flex-row">
        <div @click="downloadBackup">
          <ArrowDownTrayIcon class="w-5 h-5 p-1 box-content cursor-pointer" />
        </div>
        <div v-if="can('admin', 'user', 'backup')" @click="openRestoreModal">
          <BarsArrowUpIcon class="w-5 h-5 p-1 box-content cursor-pointer" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, defineAsyncComponent, markRaw, type PropType } from "vue";
import { mapState, mapActions } from "pinia";
import { ArchiveBoxArrowDownIcon, ArrowDownTrayIcon, BarsArrowUpIcon } from "@heroicons/vue/24/outline";
import { useAbilityStore } from "@/stores/ability";
import { useModalStore } from "@/stores/modal";
import { useBackupStore } from "../../../../stores/admin/user/backup";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    backup: { type: String, default: "" },
  },
  computed: {
    ...mapState(useAbilityStore, ["can"]),
  },
  methods: {
    ...mapActions(useModalStore, ["openModal"]),
    ...mapActions(useBackupStore, ["fetchBackupById"]),
    openRestoreModal() {
      this.openModal(
        markRaw(defineAsyncComponent(() => import("@/components/admin/user/backup/RestoreBackupModal.vue"))),
        this.backup
      );
    },
    downloadBackup() {
      this.fetchBackupById(this.backup)
        .then((response) => {
          const fileURL = window.URL.createObjectURL(new Blob([JSON.stringify(response.data, null, 2)]));
          const fileLink = document.createElement("a");
          fileLink.href = fileURL;
          fileLink.setAttribute("download", this.backup);
          document.body.appendChild(fileLink);
          fileLink.click();
          fileLink.remove();
        })
        .catch(() => {});
    },
  },
});
</script>