<script>
  import { user } from '$/client/stores.js';
  import api from '$/client/api.js';
  import { onMount } from "svelte";
  import { push } from 'svelte-spa-router';
  import { log } from "$/client/logging.js";

  /* Set this to a URL to send them if they aren't logged in. */
  export let redirect = false;

  /* Setting this to true will fill in the "no" slot with a quick message
     saying they're being redirected.
  */
  export let show_required_page = false;

  /*
   *This option is for pages that optionally authenticated,
   * but you need to load the user if they're already logged in.
   */
  export let optional = false;

  let authenticated = $user.authenticated;

  onMount(async () => {
    // there is a bug in svelte stores where directly using $user.authenticated
    // will result in undefined always even though log.debug($user) says it's true/false
    authenticated = $user.authenticated;

    // BUG: this is getting really hairy, need to refactor this
    if(authenticated === undefined) {
      // we do not know the user's login state so figure it out
      let [status, data] = await api.get('/api/login');
      let needs_redirect = redirect && (status === 401 || status === 403);

      if(status === 200) {
        Object.assign($user, data);
        $user.authenticated = true;
      } else if(optional) {
        $user.authenticated = false; // nothing else needed
      } else {
        $user.authenticated = false;
        log.debug("LoginRequired: /api/login returned", status, "json", data);

        if(needs_redirect) {
          // BUG: not sure if this should go here and only on 401/403
          window.location = redirect;
        }
      }
    } else if(optional && !$user.authenticated) {
      $user.authenticated = false; // nothing else needed
    } else if(redirect && !$user.authenticated) {
      log.debug("User not authenticated and redirection", redirect);
      window.location = redirect;
    } else {
      log.debug("User authentication state", $user);
    }
  });
</script>

{#if $user && $user.authenticated}
<slot name="yes">
</slot>
{:else if optional}
<slot name="yes">
</slot>
{:else if show_required_page}
  <main>
    <callout>
      <h1>Login Required</h1>
      <p>Redirecting you to the login now...</p>
    </callout>
  </main>
{:else}
<slot name="no">
</slot>
{/if}
