<script setup>

import { ref, useTemplateRef, onMounted } from 'vue';
import { RouterView } from 'vue-router';
import { fetcher } from '@cloudron/pankow';
import OfflineOverlay from '../components/OfflineOverlay.vue';
import ProfileModel from '../models/ProfileModel.js';

const profileModel = ProfileModel.create();

const offlineOverlay = useTemplateRef('offlineOverlay');
const ready = ref(false);
const serviceDown = ref(false);

function onOnline() {
  ready.value = true;
}

fetcher.globalOptions.errorHook = (error) => {
  // network error, request killed by browser
  if (error instanceof TypeError) {
    ready.value = false;
    return offlineOverlay.value.open();
  }

  // re-login will make the code get a new token
  if (error.status === 401) return profileModel.logout();

  // if sftp addon is down, tell the user
  if (error.status === 424) return serviceDown.value = true;

  if (error.status === 500 || error.status === 501) {
    // actual internal server error, most likely a bug or timeout log to console only to not alert the user
    if (!ready.value) {
      console.error(error);
      console.log('------\nCloudron Internal Error\n\nIf you see this, please send a mail with above log to support@cloudron.io\n------\n');
    }
  }

  if (error.status >= 502) {
    // This means the box service is not reachable. We just show offline banner for now
    ready.value = false;
    return offlineOverlay.value.open();
  }
};

onMounted(() => {
  ready.value = true;
});

</script>

<template>
  <div style="height: 100%;">
    <OfflineOverlay ref="offlineOverlay" @online="onOnline()"/>
    <div v-if="ready && serviceDown" class="service-down">
      <div>
        Unable to connect to filemanager service. Check the status and logs in <a href="/#/services">Services view</a>.
      </div>
    </div>
    <router-view v-if="ready" v-show="!serviceDown"></router-view>
  </div>
</template>

<style scoped>

.service-down {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>