<script>
  import LogOut from '$lib/components/LogOut.svelte';
  import Invites from '$lib/components/Invites.svelte';
  import ChangePassword from '$lib/components/ChangePassword.svelte';
  import PushSubscription from '$lib/components/PushSubscription.svelte';

  import { goto } from '$app/navigation';
  import * as api from '$lib/apiServer.js';

  const { data } = $props();
  const { session } = data;
  const subscription = $derived(session.push.subscription);
  const vapid = $derived(session.push.vapidKey);

  let invites = $state([]);

  async function logOut() {
    const response = await api.logOut();
    if (200 <= response.status && response.status < 300) {
      await goto('/login');
    }
  }

  async function changePassword(currentPassword, newPassword) {
    await api.changePassword(currentPassword, newPassword);
  }

  async function createInvite() {
    let response = await api.createInvite();
    if (response.status === 200) {
      invites.push(response.data);
    }
  }

  async function subscribe() {
    await session.push.subscribe();
  }
</script>

<ChangePassword {changePassword} />
<hr />
<PushSubscription {subscription} {vapid} {subscribe} />
<hr />
<Invites {invites} {createInvite} />
<hr />
<LogOut {logOut} />
