<template>
    <div v-if="!userLoaded" class="bg-neutral-100 dark:bg-neutral-900 text-primary h-screen flex justify-center items-center">
        <div>
          <Icon size="4em" name="ion:load-c" class="animate-spin" />
          <h2 class="mt-2 font-bold">Loading...</h2>
        </div>
    </div>
    <div v-else>
        <div v-if="isAuthenticated" class="bg-neutral-100 dark:bg-neutral-900 text-primary h-screen flex flex-col">
            <LayoutTopbar />
            <div class="overflow-y-auto pt-3">
                <NuxtPage />
            </div>
            <LayoutNavbar class="mt-auto" />
        </div>
        <div v-else class="bg-neutral-100 dark:bg-neutral-900 text-primary h-screen flex flex-col">
            <Login />
        </div>
    </div>
</template>

<script setup>
import { doc, getFirestore, serverTimestamp, writeBatch, collection, getDoc } from "firebase/firestore";
import { FCM } from "@capacitor-community/fcm";
import { getAuth, onAuthStateChanged, signInWithEmailAndPassword } from "firebase/auth";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
import { PushNotifications } from '@capacitor/push-notifications';
import { Device } from '@capacitor/device';

const db = getFirestore()
const route = useRoute()

const isAuthenticated = ref(false)
const user = ref('frikandel')
const registrationToken = ref('')
const auth = ref(null)
const userLoaded = ref(false)
const userData = ref(null)
const userPersons = ref([])
const userAllPersons = ref([])
const calEvents = ref([])
const news = ref(null)

const messaging = ref(null)

onMounted(() => {
    auth.value = getAuth()

    if (process.client) {
      if ('serviceWorker' in navigator && window.isSecureContext) {
        Device.getInfo().then(info => {
          if (info.platform === 'web') registerSW()
        });
        
      }
    }

    onAuthStateChanged(auth.value, async (usr) => {
        if (usr) {
            user.value = usr

            let docRef = doc(db, "users", user.value.uid);
            let docSnap = await getDoc(docRef);

            if (docSnap.exists()) {
                const data = docSnap.data()
                userData.value = data
                getPersons(userData.value.relatiecodes)
            }

            if (!userData.value.sendNews && route.path === '/news/newmessage') navigateTo('/')
            if (!userData.value.admin && route.path.startsWith('/settings/admin')) navigateTo('/')

            isAuthenticated.value = true

            logDeviceInfo()

        } else {
            isAuthenticated.value = false
            user.value = null
            userData.value = null
            userPersons.value = []
        }

        userLoaded.value = true
    })
})

const getPersons = async (persons) => {
    userPersons.value = [];

    for (let i = 0; i < persons.length; i++) {
        const docRef = doc(db, "ledenlijst", persons[i]);
        const docSnap = await getDoc(docRef);

        if (docSnap.exists()) {
            userPersons.value.push(docSnap.data())
        }
    }
}

const setupNotifications = () => {
    console.log('Initializing HomePage');

    // Request permission to use push notifications
    // iOS will prompt user and return if they granted permission or not
    // Android will just grant without prompting
    PushNotifications.requestPermissions().then(result => {
      if (result.receive === 'granted') {
        // Register with Apple / Google to receive push via APNS/FCM
        PushNotifications.register().then(() => {
          FCM.subscribeTo({ topic: "all" })
            .then((r) => alert(`Subscribed to topick all`))
            .catch((err) => console.log(err));
        });
      } else {
        // Show some error
      }
    });

    // On success, we should be able to receive notifications
    PushNotifications.addListener('registration',
      (token) => {
        // alert('Push registration success, token: ' + token.value);
	registrationToken.value = token


      	fetch('https://api.xeovalyte.com/subscribetotopic', {
        	method: 'POST',
        	headers: {
          	Authorization: 'Basic WGVvdmFseXRlOmtNKjhuRXMzNTchalJlXm1KYnZrRSFOIw==',
          	'content-type': 'application/json'
        	},
        	body: JSON.stringify({ topic: 'all', registrationToken: token.value })
      	}).then(response => response.json())
        	.then(response => {
          		console.log(response)
        	})
        	.catch(err => {
          		console.log(err)
        	});
      }
    );

    // Some issue with our setup and push will not work
    PushNotifications.addListener('registrationError',
      (error) => {
        // alert('Error on registration: ' + JSON.stringify(error));
      }
    );

    // Show us the notification payload if the app is open on our device
    PushNotifications.addListener('pushNotificationReceived',
      (notification) => {
        const { show, onClick } = useWebNotification({
          title: notification.title,
          body: notification.body,
          icon: '/ios/256.png',
          dir: 'auto',
          lang: 'en',
          renotify: true,
          tag: 'wrbapp',
        })

        show()

        onClick.on((event) => {
          navigateTo('/news')
        })
      }
    );

    // Method called when tapping on a notification
    PushNotifications.addListener('pushNotificationActionPerformed',
      (notification) => {
        navigateTo('/news')
      }
    );
}

const registerFCM = () => {
  getToken(messaging.value, { vapidKey: 'BI7l3nyGV6wJcFh7wrwmQ42W7RSXl46bmhXZJmDd4P-0K_JFP0ClTqjO-rr5H5DXBbmVR4kXwxFpUlo_d6cUy4Q' }).then((currentToken) => {
    if (currentToken) {
      console.log(currentToken)
      fetch('https://api.xeovalyte.com/subscribetotopic', {
        method: 'POST',
        headers: {
          Authorization: 'Basic WGVvdmFseXRlOmtNKjhuRXMzNTchalJlXm1KYnZrRSFOIw==',
          'content-type': 'application/json'
        },
        body: JSON.stringify({ topic: 'all', registrationToken: currentToken })
      }).then(response => response.json())
        .then(response => {
          console.log(response)
        })
        .catch(err => {
          console.log(err)
        });
    } else {
      // Show permission request UI
      console.log('No registration token available. Request permission to generate one.');
      // ...
    }
  }).catch((err) => {
    console.log('An error occurred while retrieving token. ', err);
    // ...
  });
}

const registerSW = () => {
  messaging.value = getMessaging()
  navigator.serviceWorker.register('/sw.js').catch(e => alert(e));

  onMessage(messaging.value, (payload) => {
    console.log('Message received. ', payload);

    const { show, onClick } = useWebNotification({
      title: payload.notification.title,
      body: payload.notification.body,
      icon: '/ios/256.png',
      dir: 'auto',
      lang: 'en',
      renotify: true,
      tag: 'wrbapp',
    })

    onClick.on((event) => {
      navigateTo('/news')
    })

    show()

  });
}

const logDeviceInfo = async () => {
  const info = await Device.getInfo();

  console.log(info);

  if (info.platform !== 'web') setupNotifications()
  else registerFCM()
};

const ledenlijst = ref([])

provide('firebase', { db, ledenlijst, isAuthenticated, user, userData, userPersons, auth, userAllPersons, getPersons, calEvents, news, registrationToken })
</script>
