import React from "react"
import { useEffect } from "react"
import { usePush } from "../usePush"

export default function EnableNotifications({
  onSubscribe,
}: {
  onSubscribe: () => void
}) {
  return (
    <div>
      <h1>Allow Notifications</h1>
      <div>
        Tack Up Now requires your permission to send notifications in order to
        function properly
      </div>
      <EnableButton onSubscribe={onSubscribe} />
    </div>
  )
}

function EnableButton({ onSubscribe }: { onSubscribe: () => void }) {
  const { subscribeToPush, requestPermission, canSendPush } = usePush()

  function subscribe() {
    requestPermission()
  }

  useEffect(() => {
    if (!canSendPush) return

    subscribeToPush(
      urlB64ToUint8Array(applicationServerPublicKey) as any,
      (subscription) => {
        fetch("/api/subscribe", {
          method: "POST",
          body: JSON.stringify(subscription),
        })
        onSubscribe()
      }
    )
  }, [canSendPush])

  return <button onClick={subscribe}>Enable Notifications</button>
}

const applicationServerPublicKey =
  "BDTbzdtzJxwV0sscdsXla-GKvlcxqQr7edEfkX8-papwvvV1UVc3IMyRacl1BbgTi31nWPji2wKCZkjf1l5iX7Y"

function urlB64ToUint8Array(base64String: string) {
  const padding = "=".repeat((4 - (base64String.length % 4)) % 4)
  const base64 = (base64String + padding).replace(/\-/g, "+").replace(/_/g, "/")

  const rawData = window.atob(base64)
  const outputArray = new Uint8Array(rawData.length)

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i)
  }
  return outputArray
}
