const PWA = {
    installBtnClass: "btn-install-as-app",
    deferredPrompt: null,
    displaNoneClass: Css.classes.displayNone,
    installBtnDoms: [],
    getDeferredPromptEvent: function () {
        let _this = this;
        if (_this.deferredPrompt === null) {
            window.addEventListener('beforeinstallprompt', async function (e) {
                e.preventDefault();
                _this.deferredPrompt = e;
                for (let i = 0; i < _this.installBtnDoms.length; i++) {
                    _this.installBtnDoms[i].classList.remove(_this.displaNoneClass);
                }
            });
        }
    },
    installBtnAction: function () {
        let _this = PWA;
        for (let i = 0; i < _this.installBtnDoms.length; i++) {
            _this.installBtnDoms[i].classList.add(_this.displaNoneClass);
        }
        _this.deferredPrompt.prompt();
        _this.deferredPrompt.userChoice;
        _this.deferredPrompt = null;
    },

    setBtnActions: function () {
        let _this = PWA;
        for (let i = 0; i < _this.installBtnDoms.length; i++) {
            _this.installBtnDoms[i].addEventListener('click', _this.installBtnAction, false);
        }
        window.addEventListener('appinstalled', function () {
            for (let i = 0; i < _this.installBtnDoms.length; i++) {
                _this.installBtnDoms[i].classList.add(_this.displaNoneClass);
            }
            _this.deferredPrompt = null;
        });
    },
    isStandalone: false,
    getPWADisplayMode: function () {
        this.isStandalone = window.matchMedia('(display-mode: standalone)').matches;
        if (document.referrer.startsWith('android-app://')) {
            return 'twa';
        } else if (navigator.standalone || this.isStandalone) {
            return 'standalone';
        }
        return 'browser';
    },
    init: function () {
        this.installBtnDoms = document.getElementsByClassName(PWA.installBtnClass)
        this.getDeferredPromptEvent();
        this.setBtnActions();
    }
};

PWA.init();