import { Injectable } from '@angular/core';
import { AlertController, Platform } from '@ionic/angular';
import { v4 as uuidv4 } from 'uuid'
@Injectable({
  providedIn: 'root'
})
export class WebNotificationPopupService {

  constructor( private platform: Platform) {

    navigator.serviceWorker.register(new URL('./sw.js', import.meta.url));

  }


  askNotificationPermission() {
    
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {}
    else {return false} 

    // function to actually ask the permissions
    function handlePermission(permission) {}
  
    // Let's check if the browser supports notifications
    if (!('Notification' in window)) {
      console.log("This browser does not support notifications.");
    } else {
      if(this.checkNotificationPromise()) {
        Notification.requestPermission()
        .then((permission) => {
          handlePermission(permission);
        })
      } else {
        Notification.requestPermission(function(permission) {
          handlePermission(permission);
        });
      }
    }
  }


  private checkNotificationPromise() {
    try {
      Notification.requestPermission().then();
    } catch(e) {
      return false;
    }

    return true;
  }

  sendNotification(e) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {}
    else {return false} 

    Notification.requestPermission((result) => {
      if (result === 'granted') {
        navigator.serviceWorker.ready.then((registration)=> {

          registration.showNotification(e.Object,  {
            body: e.Service,
            icon: 'assets/icon/favicon.png',
            requireInteraction: true,
            tag: 'require-interaction'+uuidv4(),
            // actions: [
            //   {action: 'like', title: 'Like', icon: 'https://example/like.png'},
            //   {action: 'reply', title: 'Reply', icon: 'https://example/reply.png'}
            // ]
          }).then(e =>{
            console.log(e)
          })
  
        });
   
      }
    });


    
  }
}
