<script setup lang="ts">
import { ref, computed, watch } from "vue";
import type { AppNotification } from "@/interfaces";
import { useMainStore } from "@/stores/main";
import { storeToRefs } from "pinia";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const show = ref(false);
const showProgress = ref(false);
const currentNotification = ref<AppNotification | false>(false);
const currentNotificationFlag = ref(false);

const mainStore = useMainStore();
const mainStoreRef = storeToRefs(mainStore);

const currentNotificationContent = computed(() => {
  return (currentNotification.value && currentNotification.value.content) || "";
});
const currentNotificationColor = computed(() => {
  return (
    (currentNotification.value && currentNotification.value.color) || "info"
  );
});

const firstNotification = mainStoreRef.readFirstNotification;

async function hide() {
  show.value = false;
  await new Promise<void>((resolve, reject) =>
    setTimeout(() => resolve(), 500)
  );
}
async function close() {
  await hide();
  await removeCurrentNotification();
}

async function removeCurrentNotification() {
  if (currentNotification.value) {
    mainStore.removeNotification(currentNotification.value);
  }
}

watch(firstNotification, async (newNotification, oldNotification) => {
  if (newNotification !== currentNotification.value) {
    await setNotification(newNotification);
    if (newNotification) {
      mainStore.dispatchRemoveNotification({
        notification: newNotification,
        timeout: 1000,
      });
    }
  }
});

async function setNotification(notification: AppNotification | false) {
  if (show.value) {
    await hide();
  }
  if (notification) {
    currentNotification.value = notification;
    showProgress.value = notification.showProgress || false;
    show.value = true;
  } else {
    currentNotificationFlag.value = false;
  }
}
</script>

<template>
  <div>
    <v-snackbar auto-height :color="currentNotificationColor" v-model="show">
      <v-progress-circular
        class="mx-3"
        indeterminate
        v-show="showProgress"
      ></v-progress-circular
      >{{ currentNotificationContent }}
      <template v-slot:actions>
        <v-btn flat @click.native="close">{{ t("close") }}</v-btn>
      </template>
    </v-snackbar>
  </div>
</template>
