import { EventEmitter } from 'events';
import { NotificationAction, NotificationDispatcher } from "./typings";
import {Nudge} from "../../core/repositories/nudges/typings";

class CfBrowserNotification extends EventEmitter implements NotificationDispatcher {
    private allowed = false
    public clickedNotifications = {}

    public constructor() {
        super()

        if (this.permissionNeedsUserInteraction()) {
            document.querySelector('body').addEventListener('click', () => {
                this.requestUserPermission()
            }, true)
        } else {
            this.requestUserPermission()
        }
    }

    permissionNeedsUserInteraction(): boolean {
        const isFirefox = () => {
            // extracted from https://github.com/arasatasaygin/is.js/blob/master/is.js
            // another approach would be:
            // var isFirefox = typeof InstallTrigger !== 'undefined';

            return navigator.userAgent.toLowerCase().match(/(?:firefox|fxios)\/(\d+)/) !== null
        }

        return isFirefox()
    }

    requestUserPermission() {
        Notification.requestPermission((result) => {
            this.allowed = result === 'granted'
        });
    }

    show(nudge: Nudge, id: number) {
        const options = {
            nudge,
            requireInteraction: true
        }

        if (!this.allowed) {
            console.warn('--- NOT ALLOWED TO SHOW NOTIFICATIONS ---')
            this.emit(NotificationAction.Block, id)
            return
        }

        const notification = new Notification(nudge.nd.message.title, options)

        if(notification){
            this.emit(NotificationAction.Shown, id)
        }

        // the behavior when clicking on the notification is like that:
        //    - [click on the notification] dispatched onclick and onclose
        //    - [click on the "x" to close it] dispatched onclose
        //
        // neither stopInmediatePropagation nor stopPropagation change this behaviour
        notification.onclick = (evt: Event) => {
            this.clickedNotifications[id] = true

            evt.stopPropagation()
        }

        notification.onclose = (evt: Event) => {

            if (this.clickedNotifications[id]) {
                // notification has been clicked
                this.emit(NotificationAction.Open, id)
            } else {
                // notification has been discarded
                this.emit(NotificationAction.Discard, id)
            }

        }

    }

}

export default CfBrowserNotification
