<script>
  import Header from '$lib/navigation/header.svelte';
  import Loading from '$lib/navigation/loading.svelte';
  import Nav from '$lib/navigation/nav.svelte';
  import { uuid } from '$lib/stores/uuid.js';
  import { onMount } from 'svelte';

  const title = 'Registration';
  let state = '';
  let isLoading = true;

  async function getUUID() {
    return new URLSearchParams(window.location.search).get('key');
  }

  async function submit(id) {
    const url = 'https://owlboard.info/api/v2/user/register';
    const request = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        uuid: id
      })
    };
    const res = await fetch(url, request);
    const body = await res.json();
    if (body.api_key) {
      uuid.set(body.api_key);
      return 201;
    }
    return res.status;
  }

  onMount(async () => {
    const id = (await getUUID()) || '';
    if (id == '' || !id) {
      state = 'none';
      isLoading = false;
      return;
    }
    const status = await submit(id);
    if (status == 201) {
      console.log('Registered Successfully');
      state = 'done';
    } else if (status == 401) {
      console.log('Invalid Key');
      state = 'unauth';
    } else {
      console.log('Error');
      state = 'error';
    }
    isLoading = false;
  });
</script>

<Header {title} />
{#if isLoading}
  <Loading />
{/if}
{#if state == 'none'}
  <p>Unable to read your access key.</p>
  <p>Please click the link in your email again.</p>
{:else if state == 'unauth'}
  <p>Your link is not valid, links expire after 30 minutes.</p>
  <p>You can try to register again.</p>
{:else if state == 'error'}
  <p>There was an error on our end, please try again later</p>
{:else if state == 'done'}
  <p>You are now logged in</p>
{/if}
<Nav />

<style>
  p {
    margin: 14px;
  }
</style>
