<script>
  import { onMount } from "svelte";
  import Toggle from '$lib/components/Toggle.svelte';

  let subscriptionJson = $state(null);

  function doSubscribe() {
    navigator.serviceWorker.ready
      .then(async (registration) => {
        const response = await fetch("/api/vapid");
        // and if we fail to get it?
        const vapidPublicKey = await response.text();
        const convertedVapidKey = vapidPublicKey;
        return registration.pushManager.subscribe({
          userVisibleOnly: true,
          applicationServerKey: convertedVapidKey
        });
      }).then((subscription) => {
        const subJson = subscription.toJSON();
        subscriptionJson = {
          endpoint: subJson.endpoint,
          p256dh: subJson.keys.p256dh,
          auth: subJson.keys.auth,
        };
        return fetch("/api/push", {
          method: "post",
          headers: { "Content-type": "application/json" },
          body: JSON.stringify(subscriptionJson),
        });
      });
  }

  function doUnsubscribe() {
    navigator.serviceWorker.ready
      .then((registration) => {
        return registration.pushManager.getSubscription();
      }).then((subscription) => {
        const { endpoint } = subscription.toJSON();
        return subscription.unsubscribe()
          .then(() => {
            fetch("/api/push", {
              method: "delete",
              headers: { "Content-type": "application/json" },
              body: JSON.stringify({ endpoint }),
            });
            subscriptionJson = null;
          });
      });
  }

  function toggleSub() {
    if (subscriptionJson !== null) {
      doUnsubscribe();
    } else {
      doSubscribe();
    }
  }

  onMount(() => {
    navigator.serviceWorker.ready.then((registration) => {
      return registration.pushManager.getSubscription();
    }).then((subscription) => {
      if (subscription) {
        subscriptionJson = JSON.parse(JSON.stringify(subscription));
      }
    });
  });
</script>

<h2>Enable notifications</h2>

<p>
  {#if subscriptionJson === null}
    Notifications are currently disabled.
  {:else}
    Notifications are currently enabled.
  {/if}
</p>
<button class="btn" onclick="{toggleSub}">
  {#if subscriptionJson === null}
    Enable notifications
  {:else}
    Disable notifications
  {/if}
</button>

<h2>Notify me when:</h2>

<Toggle
    name="channel_created"
    text="A new channel is created"
    onclick={async () => {}}
/>
<Toggle
    name="message_arrives"
    text="A new message arrives in a channel"
    onclick={async () => {}}
/>
<Toggle
    name="message_arrives_username"
    text="A new message containing your username arrives in a channel"
    onclick={async () => {}}
/>
<Toggle
    name="message_arrives_keyword"
    text="A new message containing a keyword you have configured arrives in a channel"
    onclick={async () => {}}
/>
<Toggle
    name="own_message_stitched"
    text="A message you wrote is stitched"
    onclick={async () => {}}
/>
<Toggle
    name="flagged_message_stitched"
    text="A message you have flagged is stitched"
    onclick={async () => {}}
/>
