<script setup>

import { ref, useTemplateRef } from 'vue';
import { Dialog } from '@cloudron/pankow';

const dialog = useTemplateRef('dialog');

const status = ref(0);
const message = ref('');
const stackTrace = ref('');

async function onError(error) {
  // this is handled by the fetcher global error hook
  if (error.status === 401 || error.status >= 502 || error instanceof TypeError) return;

  console.error(error);

  status.value = error.status || 0;
  message.value = error.body?.message || error.message || 'unkown';

  let stack = '';
  if (error.stack) stack = error.stack;
  else stack = (new Error()).stack;

  if (stack.indexOf('Error') === 0) { // chrome v8
    stackTrace.value = stack.split('\n').slice(2, 7).map(l => l.slice('    at '.length).split(' ')[0] + '()').join('\n');
  } else { // firefox and safari
    stackTrace.value = stack.split('\n').slice(1, 7).map(l => l.split('@')[0] + '()').join('\n');
  }

  dialog.value.open();
}

if (!window.cloudron) window.cloudron = {};
window.cloudron.onError = onError;

</script>

<template>
  <Dialog ref="dialog" title="Unhandled error"
    :reject-label="$t('main.dialog.close')"
  >
    <div>
      <label v-if="status">Status:</label>
      <pre v-if="status">{{ status }}</pre>
      <label>Details:</label>
      <pre>{{ message }}</pre>
      <label>Trace:</label>
<pre>
{{ stackTrace }}
...
</pre>
    </div>
  </Dialog>
</template>
