/* eslint-disable no-console */

import { register } from "register-service-worker";
import axios from "axios";
import firebase from "firebase/app";
import "firebase/messaging";

if (process.env.NODE_ENV === "production") {
  if (Notification.permission === 'granted') {
    const firebaseConfig = {
      apiKey: "AIzaSyB4IvN1P0u7nWZx96lAKWNix7EOx0tuX48",
      authDomain: "gabenparadise-c658e.firebaseapp.com",
      databaseURL: "https://gabenparadise-c658e.firebaseio.com",
      projectId: "gabenparadise-c658e",
      storageBucket: "gabenparadise-c658e.appspot.com",
      messagingSenderId: "338698464238",
      appId: "1:338698464238:web:da7df8af54802ab19efcff"
    };

    if (!firebase.apps.length) {
      firebase.initializeApp(firebaseConfig);
    }
  }

  register(`${process.env.BASE_URL}service-worker.js`, {
    ready() {
      console.log(
        "App is being served from cache by a service worker.\n" +
        "For more details, visit https://goo.gl/AFskqB"
      );

      Notification.requestPermission(function (status) {
        console.log("Status ", status);
      })
    },
    registered($registration) {
      if (Notification.permission === 'granted') {
        const messaging = firebase.messaging.isSupported() ? firebase.messaging() : null
        if (messaging != null) {
          console.log("Service worker has been registered. ", $registration);
          messaging.useServiceWorker($registration);
          messaging.usePublicVapidKey('BEbiSQ7ishlWlO7v-_EJW3iFk6WmgdSFrPgfXsjLNflqljBqWEZwv-4iyaTaYYE1VM2y1fX9V50QoZ0c8ft5C0s');
          
          messaging.getToken().then(function (token) {
            console.log("Token: ", token)
            console.log(JSON.stringify({ "token": token }));
            
            axios.post('https://dev.steelants.cz/vasek/gabenparadise/api/subscribe', { 
              "token" : token
            }, {
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
              }
            }
            ).then(function (response) {
              console.log(response);
            }).catch(function (error) {
              console.log(error);
            });
          });
        } else {
          document.getElementById("sub-identifi").className = "fa fa-bell-slash-o bell"; 
        }
      } else {
        document.getElementById("sub-identifi").className = "fa fa-bell-slash-o bell"; 
      }
    },
    cached() {
      console.log("Content has been cached for offline use.");
    },
    updatefound() {
      console.log("New content is downloading.");
    },
    updated() {
      console.log("New content is available; please refresh.");
      //window.location.reload(true);
    },
    offline() {
      console.log(
        "No internet connection found. App is running in offline mode."
      );
    },
    error(error) {
      console.error("Error during service worker registration:", error);
    }
  });
}
