<script setup>

import { useTemplateRef, ref } from 'vue';
import { fetcher, Spinner, Dialog } from 'pankow';
import { API_ORIGIN } from '../constants.js';

const emits = defineEmits(['online']);

const dialog = useTemplateRef('dialog');
const isOpen = ref(false);

async function waitForOnline() {
  let result;
  try {
    result = await fetcher.get(`${API_ORIGIN}/api/v1/cloudron/status`, {});
    // eslint-disable-next-line no-unused-vars
  } catch (e) {
    return setTimeout(waitForOnline, 5000);
  }

  if (result.status !== 200) return setTimeout(waitForOnline, 5000);

  // back online
  emits('online');
  dialog.value.close();
  isOpen.value = false;
}

defineExpose({
  open() {
    if (isOpen.value) return;

    isOpen.value = true;

    dialog.value.open();
    waitForOnline();
  }
});

</script>

<template>
 <Dialog ref="dialog" :modal="true">
  <div style="display: flex; flex-direction: column; align-items: center;">
    <Spinner class="pankow-spinner-large" style="margin: 20px"/>
    <a href="https://docs.cloudron.io/troubleshooting/" target="_blank">{{ $t('main.offline') }}</a>
  </div>
 </Dialog>
</template>
