//var firebase = require("firebase");
import firebase from "firebase/app"
import 'firebase/database'
import 'firebase/messaging'
//based on 
//https://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript
class Singleton {
    // Properties & Methods
    messaging;
    fcmToken;
    
    constructor() {
        console.log('firebase-client constructor')
        if (!Singleton.instance) {
            Singleton.instance = this
        }
        // Initialize object
        if (!firebase.messaging.isSupported()) {
            console.log('firebase.messaging not supported')
            return;
        }
        
        let config = {
            apiKey: "AIzaSyArZab_4hUDgksQ4Dqdwv970JyRSlbGaKY",
            authDomain: "edeclicpwa.firebaseapp.com",
            databaseURL: "https://edeclicpwa.firebaseio.com",
            projectId: "edeclicpwa",
            storageBucket: "edeclicpwa.appspot.com",
            messagingSenderId: "130215947970"
        }
        firebase.initializeApp(config);

        navigator.serviceWorker
            .register('/service-worker.js')
            .then((registration) => {
                firebase.messaging().useServiceWorker(registration);
            });
        this.messaging = firebase.messaging();
        this.messaging.usePublicVapidKey('BEiMSVYvblP5oKcIY7b90r-5xLk1QYDra1sSdZHdaynihcb3Hx9wdZdI9IUHmbqureB_-IpOFKpm7arBB93J3rk');
        console.log('FireBase Singleton Initialized')
        return Singleton.instance
    }
    
    isSupported()
    {
        this.messaging.app.firebase_.messaging.isSupported()
    }

    async requestPermission() {
        console.log('Requesting permission...');

        this.messaging.requestPermission().then(function () {
            console.log('Notification permission granted.');
            // TODO(developer): Retrieve an Instance ID token for use with FCM.
            // [START_EXCLUDE]
            // In many cases once an app has been granted notification permission, it
            // should update its UI reflecting this.
            //        resetUI();
            // [END_EXCLUDE]
        }).catch(function (err) {
            console.log('Unable to get permission to notify.', err);
        });
    }

    async askForToken() {
        var res = await this.messaging.getToken().then(async (currentToken) => {
            if (currentToken) {
                // console.log(currentToken)
                //  this.fcmToken = currentToken;
                await this.sendTokenToServer(currentToken);
                return currentToken;
            }
            else {
                // Show permission request.
                console.log('No Instance ID token available. Request permission to generate one.');
                this.requestPermission()
                // Show permission UI.
                // updateUIForPushPermissionRequired();
                await this.setTokenSentToServer(false);
            }
        }).catch(async (err) => {
            console.log('An error occurred while retrieving token. ', err);
            // showToken('Error retrieving Instance ID token. ', err);
            await this.setTokenSentToServer(false);
        })
        console.log("Token : ")
        console.log(res);
        return res
    }
    async deleteToken() {
        // Delete Instance ID token.
        // [START delete_token]
        this.messaging.getToken().then(async (currentToken) => {
            this.messaging.deleteToken(currentToken).then(async () => {
                console.log('Token deleted.');
                await this.setTokenSentToServer(false);
                // [START_EXCLUDE]
                // Once token is deleted update UI.
                //resetUI();
                // [END_EXCLUDE]
            }).catch((err) => {
                console.log('Unable to delete token. ', err);
            });
            // [END delete_token]
        }).catch((err) => {
            console.log('Error retrieving Instance ID token. ', err);
            //showToken('Error retrieving Instance ID token. ', err);
        });
    }
    async sendTokenToServer(currentToken) {
        var tokenSent = await this.isTokenSentToServer()
        if (!tokenSent) {
            console.log('Sending token to server...');
            firebase.database().ref('subscription/' + currentToken).set({
                general: true,
                pwa: true,
                boats: false
            });

            this.setTokenSentToServer(true);
        } else {
            console.log('Token already sent to server so won\'t send it again ' +
                'unless it changes');
        }
    }
    async isTokenSentToServer() {
        return window.localStorage.getItem('sentToServer') === '1';
    }
    async setTokenSentToServer(sent) {
        window.localStorage.setItem('sentToServer', sent ? '1' : '0');
    }
}

const instance = new Singleton()
Object.freeze(instance)

export default instance
