import BusinessTypeSetting, { BusinessEnum } from "@/_BusinessTypeSetting/BusinessTypeSetting";
// import { initializeApp } from "firebase/app";
// import { getMessaging, getToken } from "firebase/messaging";


// Public Key:
// BPxB0rLAHuETo-CFw6xe2_ZlQ8qm6WAg-i45UTStiYYU0pPYR1wuO0jwt8S_gRl_hYFNoI1l0l4vFksncHC5yUs

// Private Key:
// 2-dDtLj8ibIOj51RD9ASV3DtTjkmFQyn_zId3V4OtwA
const applicationServerPublicKey: string = `BPxB0rLAHuETo-CFw6xe2_ZlQ8qm6WAg-i45UTStiYYU0pPYR1wuO0jwt8S_gRl_hYFNoI1l0l4vFksncHC5yUs`;
const swjsPath: string = "./assets/sw.js";

export function PWAOnLoad() {
	if (BusinessTypeSetting.UseServerType !== BusinessEnum.ServerType.Internal_Dev) {
		return;
	}
	if ("serviceWorker" in navigator) {
		navigator.serviceWorker
			.register(swjsPath)
			.then((reg: ServiceWorkerRegistration) => {
				console.debug("Service Worker Registered");
				askForNotificationPermission();
				setFCM(reg);
			});
	}
}

/**
 *
 * @url https://stackoverflow.com/questions/50399170/what-bearer-token-should-i-be-using-for-firebase-cloud-messaging-testing
 */
function setFCM(reg: ServiceWorkerRegistration) {
	// Your web app's Firebase configuration
	// For Firebase JS SDK v7.20.0 and later, measurementId is optional
	const firebaseConfig = {
		apiKey: "AIzaSyAZ1Hkr-tmF5xqnNWy0jprXDy1xEZUyYy8",
		authDomain: "jm-webpush.firebaseapp.com",
		projectId: "jm-webpush",
		storageBucket: "jm-webpush.appspot.com",
		messagingSenderId: "903093229309",
		appId: "1:903093229309:web:54a3006e1e1afdeaefd094",
		measurementId: "G-SBKR7HBFBB"
	};

	// // Initialize Firebase
	// const app = initializeApp(firebaseConfig);
	// // const analytics = getAnalytics(app);

	// // Initialize Firebase Cloud Messaging and get a reference to the service
	// const messaging = getMessaging(app);

	// // Add the public key generated from the console here.
	// getToken(messaging, { vapidKey: applicationServerPublicKey, serviceWorkerRegistration: reg }).then((currentToken) => {
	// 	if (currentToken) {
	// 		// Send the token to your server and update the UI if necessary
	// 		console.debug(`[Test] Firebase Token: ${currentToken}`);
	// 	} else {
	// 		// Show permission request UI
	// 		console.debug("[Test] No registration token available. Request permission to generate one.");
	// 		// ...
	// 	}
	// }).catch((err) => {
	// 	console.debug("[Test] An error occurred while retrieving token. ", err);
	// 	// ...
	// });
}

export function askForNotificationPermission() {
	if ("Notification" in window) {
		// console.log("Notification permission default status:", Notification.permission);
		Notification.requestPermission(function (result: NotificationPermission) {
			// 這裡result只會有兩種結果：一個是用戶允許(granted)，另一個是用戶封鎖(denied)
			// console.log("Notification permission status:", status);
			if (result !== "granted") {
				console.log("No notification permission granted!");
			} else {
				displayConfirmNotification();
			}
		});
	}
}

function displayConfirmNotification() {
	// pushNotification("成功訂閱!! (from Service Worker)", "您已成功訂閱我們的推播服務!");
}

export function pushNotification(title: string, content: string) {
	if ("serviceWorker" in navigator && Notification.permission == "granted") {
		const options = {
			body: content,
			icon: "../img/jpg/logo512.jpg"
		};
		// navigator.serviceWorker.ready.then(function (swreg: ServiceWorkerRegistration) {
		navigator.serviceWorker.getRegistration(swjsPath).then(function (swreg: ServiceWorkerRegistration) {
			swreg.showNotification(title, options);
		});
	}
}