<template>
  <QuickNav />

  <!-- CONTENT -->
  <section id="Content" class="p-6 pb-24">
    <!-- Breadcrumb -->
    <div class="mb-8">
      <!-- Back -->
      <div class="text-lg text-center font-light relative px-7">
        <h1
          class="text-lg text-center px-2 py-1 absolute -left-2 -top-1"
          @click="$router.back()"
        >
          <fa icon="chevron-left" class="fa-fw"></fa>
        </h1>
      </div>

      <!-- Heading -->
      <h1 id="ViewHeading" class="text-4xl text-center font-light pt-4 mb-8">
        Notification Help
      </h1>
    </div>

    <div>
      <p>Here are ways to get notifications working.</p>

      <h2 class="text-xl font-semibold">Test</h2>
      <p>Somehow call the service-worker self.showNotification</p>
      <button
        @click="showTestNotification()"
        class="block w-full text-center text-md uppercase bg-slate-500 text-white px-1.5 py-2 rounded-md mb-2"
      >
        See a Test Notification
      </button>

      <h2 class="text-xl font-semibold">Check OS-level permissions</h2>
      <div>
        Walk-throughs & screenshots, maybe for all combinations of OS &
        browsers.
        <div>
          <h3 class="text-lg font-semibold">Mobile Phone - Apple iOS</h3>
          <div>
            Notifications require iOS 16.4 or higher. To check your iOS version,
            go to Settings > General > About > Software Version.
          </div>

          <h3 class="text-lg font-semibold">Mobile Phone - Google Android</h3>
          <div>See the browser section.</div>

          <h3 class="text-lg font-semibold">Desktop - Mac</h3>
          <div>Requires Mac OS 13.</div>
        </div>
      </div>

      <h2 class="text-xl font-semibold">Check browser-level permissions</h2>
      <p>Walk-throughs & screenshots for browser settings</p>
      <div>
        <div>
          <h3 class="text-lg font-semibold">Mobile Phone - Apple iOS</h3>
          <div>Make sure your OS (above) supports it.</div>

          <h3 class="text-lg font-semibold">Mobile Phone - Android</h3>
          <div>
            Chrome requires version 50. Hold icon, select "App info", and enable
            notifications.
          </div>
        </div>
      </div>

      <h2 class="text-xl font-semibold">Explain full reset to start again</h2>
      <p>
        Walk-throughs for clearing everything & subscribing anew to get a
        message
      </p>

      <h2 class="text-xl font-semibold">Auto-detection</h2>
      <p>Show results of auto-detection whether they're turned on</p>

      <button
        @click="alertWebPushSubscription()"
        class="block w-full text-center text-md uppercase bg-slate-500 text-white px-1.5 py-2 rounded-md mb-2"
      >
        Show Subscription from Web Push Server
      </button>

      <button
        @click="sendTestWebPushMessage()"
        class="block w-full text-center text-md uppercase bg-slate-500 text-white px-1.5 py-2 rounded-md mb-2"
      >
        Send Myself a Test Web Push Message
      </button>
    </div>
  </section>
</template>
<script lang="ts">
import axios from "axios";
import { Component, Vue } from "vue-facing-decorator";

import QuickNav from "@/components/QuickNav.vue";
import { db } from "@/db/index";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import { DEFAULT_PUSH_SERVER } from "@/constants/app";

// eslint-disable-next-line @typescript-eslint/no-var-requires
const Buffer = require("buffer/").Buffer;

interface Notification {
  group: string;
  type: string;
  title: string;
  text: string;
}

@Component({ components: { QuickNav } })
export default class HelpNotificationsView extends Vue {
  $notify!: (notification: Notification, timeout?: number) => void;

  subscription: PushSubscription | null = null;

  async mounted() {
    try {
      const registration = await navigator.serviceWorker.ready;
      this.subscription = await registration.pushManager.getSubscription();
    } catch (error) {
      console.error("Mount error:", error);
    }
  }

  alertWebPushSubscription() {
    console.log(
      "Web push subscription:",
      JSON.parse(JSON.stringify(this.subscription)), // gives more info than plain console logging
    );
    alert(JSON.stringify(this.subscription));
  }

  async sendTestWebPushMessage() {
    if (!this.subscription) {
      this.$notify(
        {
          group: "alert",
          type: "danger",
          title: "Not Subscribed",
          text: "You must enable notifications before testing the web push.",
        },
        -1,
      );
      return;
    }

    try {
      await db.open();
      const settings = await db.settings.get(MASTER_SETTINGS_KEY);
      let pushUrl: string = DEFAULT_PUSH_SERVER as string;
      if (settings?.webPushServer) {
        pushUrl = settings.webPushServer;
      }

      // This is shared with the service worker and should be a constant. Look for the same name in additional-scripts.js
      // Use something other than "Daily Update" https://gitea.anomalistdesign.com/trent_larson/py-push-server/src/commit/3c0e196c11bc98060ec5934e99e7dbd591b5da4d/app.py#L213
      const DIRECT_PUSH_TITLE = "DIRECT_NOTIFICATION";

      const auth = Buffer.from(this.subscription.getKey("auth"));
      const authB64 = auth
        .toString("base64")
        .replace(/\+/g, "-")
        .replace(/\//g, "_")
        .replace(/=+$/, "");
      const p256dh = Buffer.from(this.subscription.getKey("p256dh"));
      const p256dhB64 = p256dh
        .toString("base64")
        .replace(/\+/g, "-")
        .replace(/\//g, "_")
        .replace(/=+$/, "");
      const newPayload = {
        endpoint: this.subscription.endpoint,
        keys: {
          auth: authB64,
          p256dh: p256dhB64,
        },
        message: "This is a test message, triggered by you.",
        title: DIRECT_PUSH_TITLE,
      };
      console.log("Sending a test web push message:", newPayload);
      const payloadStr = JSON.stringify(newPayload);
      const response = await axios.post(
        pushUrl + "/web-push/send-test",
        payloadStr,
        {
          headers: {
            "Content-Type": "application/json",
          },
        },
      );

      console.log("Got response from web push server:", response);

      this.$notify(
        {
          group: "alert",
          type: "success",
          title: "Test Web Push Sent",
          text: "Check your device for the test web push message.",
        },
        -1,
      );
    } catch (error) {
      console.error("Got an error sending test notification:", error);
      this.$notify(
        {
          group: "alert",
          type: "danger",
          title: "Error Sending Test",
          text: "Got an error sending the test web push notification.",
        },
        -1,
      );
    }
  }

  showTestNotification() {
    navigator.serviceWorker.ready
      .then((registration) => {
        return registration.showNotification("It Worked", {
          body: "This is your test notification.",
        });
      })
      .then(() => {
        this.$notify(
          {
            group: "alert",
            type: "success",
            title: "Sent",
            text: "A notification was triggered, so one should show on your device soon.",
          },
          5000,
        );
      })
      .catch((error) => {
        console.error("Got a notification error:", error);
        this.$notify(
          {
            group: "alert",
            type: "danger",
            title: "Failed",
            text: "Got an error sending a notification.",
          },
          -1,
        );
      });
  }
}
</script>
