const timezone = (function () {

    const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    let mainDialog = null;

    const showModal = () => {
        const modal = $("<div></div>")
            .dialog_modal({
                passedArgs: ['', [], {
                    header: "<h2>Change Timezone</h2>",
                    body_url: MP_SITE_URL + '/timezone/tz_modal?new=' + timezone
                }],
                addBodyClass: 'form-buttons'
            })
        .data('ui-dialog_modal');
        mainDialog = modal.instance()
    }

    let storage = localStorage;
    let tzStorageKey = 'timeZone';

    return {
        checkTimeZoneChange: async function () {

            if (!this.isTzSeen()) {
                return false;
            }

            // check if timezone is changed
            if ((await this.getProfileTimeZone())?.value == timezone) {
                return false;
            }

            if (await this.isUseBrowserTime() == 1) {
                this.updateTimezone(timezone);
                this.setTzSeen();
                return false;
            }

            // if user has selected never show again option then skip
            if (await this.isNeverAskAgain() == 1) {
                return false;
            }

            if (this.isOtherModalsOnScreen()) {
                return  false;
            }

            // if timezone is not valid then skip
            if (await this.isValidTimeZone() == 0) {
                return false;
            }

            if (modalThreshold.canBeShown()){
                showModal();
                this.setTzSeen();
                modalThreshold.setShownTime()
            }
        },

        isOtherModalsOnScreen: () => {
            /**
             * Do not show tz pop-up if is not initialized yet and current application is dashboard
             * OR .modal-body class is visible
             * OR tour guide is started
             */
            return (sessionStorage.getItem('tour_session_initialized') == 'false' &&
                window.location.pathname.search('dashboard') > 0) ||
                $('.modal-body').is(":visible") ||
                (localStorage.getItem('tourStarted') == 'true' && localStorage.getItem('tour_end') != 'yes');
        },

        isNeverAskAgain: async () => {
            let neverAskAgain = 0;
            await $.get('/timezone/neverAskAgain')
                .done((response) => {
                    neverAskAgain = response
                }).fail((error) => {
                    notify.error(error.responseText);
                });
            ;
            return neverAskAgain;
        },

        isUseBrowserTime: async () => {
            let useBrowserTime = 0;
            await $.get('/timezone/useBrowserTime')
                .done((response) => {
                    useBrowserTime = response
                }).fail((error) => {
                    notify.error(error.responseText);
                });
            ;
            return useBrowserTime;
        },

        isValidTimeZone: async () => {
            let isValid = 0;
            await $.get('/timezone/isValidTimeZone?tz=' + timezone)
                .done((response) => {
                    isValid = response;
                }).fail((error) => {
                    notify.error(error.responseText);
                });
            ;
            return isValid;
        },

        isTzSeen: function () {
            return storage.seen_tz_local == undefined || storage.seen_tz_local == false;
        },

        setTzSeen: () => {
            storage.seen_tz_local = true;
        },

        removeTimeZoneFromStorage: () => storage.removeItem(tzStorageKey),

        addTimeZoneToStorage: (tz) => storage.setItem(tzStorageKey, tz),

        getTimeZoneFromStorage: () => {
            try {
                const tz = storage.getItem(tzStorageKey);
                if (!tz) return null;
                return JSON.parse(tz);
            } catch (e) {
                return null;
            } 
        },

        updateTimezone: function(tz) {
            common.globalSpinner.show();
            $.post('/timezone/profile_timezone', {'time_zone': tz})
                .done(() => {
                    if (mainDialog !== null) {
                        mainDialog.modal('hide');
                    }
                    this.removeTimeZoneFromStorage();
                    common.globalSpinner.hide();
                })
                .fail((error) => {
                    notify.error(error.responseText);
                });
        },

        getProfileTimeZone: async function()  {
            let tz = this.getTimeZoneFromStorage();
            if (tz == null) {
                try {
                    tz = await $.getJSON('/timezone/currentTimezone');
                    this.addTimeZoneToStorage(JSON.stringify(tz));
                } catch (error) {
                    notify.error(error.responseText);
                }
            }

            return tz;
        },


        neverAskAgain: () => {
            $.post('/timezone/neverAskAgain')
                .done(() => {
                    mainDialog.modal('hide');
                })
                .fail((error) => {
                    notify.error(error.responseText);
                });
        },

        useBrowserTime: () => {
            $.post('/timezone/useBrowserTime')
                .fail((error) => {
                    notify.error(error.responseText);
                });
        }
    };
})();
/**
 * preload timezone into localStorage
 */
timezone.getProfileTimeZone();
timezone.checkTimeZoneChange();
