<template>
  <v-snackbar
    v-model="updateFound"
    content-class="update"
    :timeout="-1"
    location="bottom end"
    rounded="lg"
    min-width="240"
    elevation="0"
    variant="elevated"
  >
    <v-alert
      v-model="updateFound"
      color="minsk_900"
      prominent
      rounded="lg"
      icon="browser_updated"
    >
      <div class="text-subtitle-2">
        <span>{{ t('texts.updateDetected') }}</span>
        <br />
        <span>{{ t('texts.pleaseUpdateAsap') }}</span>
      </div>
      <template #append>
        <v-btn
          v-if="!updateInstalled"
          :loading="true"
          disabled
        >
          <span>{{ t('labels.installing') }}</span>
        </v-btn>
        <v-btn
          v-if="updateInstalled"
          data-testid="update"
          color="minsk_500"
          variant="flat"
          size="large"
          :loading="updateLoading"
          @click="completeRegistration"
        >
          <span>{{ t('labels.update') }}</span>
        </v-btn>
      </template>
    </v-alert>
  </v-snackbar>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { ServiceWorkerService } from '@/services/service-worker.service';
import { useI18n } from 'vue-i18n';

let registration: ServiceWorkerRegistration | undefined = undefined;

const { t } = useI18n();

const updateFound = ref<boolean>(false);
const updateInstalled = ref<boolean>(false);
const updateLoading = ref<boolean>(false);

onMounted(async () => {
  registration = await ServiceWorkerService.Instantiate().getRegistration();
  if (registration) {
    setupCheck(registration);
  }
});

function setupCheck(registration: ServiceWorkerRegistration) {
  registration.addEventListener('updatefound', () => {
    updateFound.value = true;
    if (registration.installing) {
      registration.installing.addEventListener('statechange', () => {
        if (registration.waiting) {
          updateInstalled.value = true;
          console.log('[app]Service Worker update available');
        }
      });
    }
  });
  setInterval(() => {
    registration.update();
  }, 1000);
}

function completeRegistration() {
  updateLoading.value = true;
  registration?.waiting?.postMessage('SKIP_WAITING');
}
</script>

<style lang="scss">
.update .v-snackbar__content {
  padding: 0 !important;
}
</style>
