/**
 * Front Script
 */

(function ($, window, document, pluginObject) {
    "use strict";

    let audioElement,
        storageSoundKey = 'olistener_sound_enabled',
        storageNotifierKey = 'olistener_notifier_enabled',
        audioUnlocked = false,
        pendingAlertPlayback = false,
        isSoundPersistenceEnabled = !!pluginObject.persistSoundState,
        saveSoundState = function (isEnabled) {
            if (!isSoundPersistenceEnabled || !window.localStorage) {
                return;
            }

            try {
                window.localStorage.setItem(storageSoundKey, isEnabled ? '1' : '0');
            } catch (e) {
                // Silently ignore storage errors (private mode, quota, etc).
            }
        },
        getSavedSoundState = function () {
            if (!isSoundPersistenceEnabled || !window.localStorage) {
                return null;
            }

            try {
                let storedState = window.localStorage.getItem(storageSoundKey);
                if (storedState === '1') {
                    return true;
                }
                if (storedState === '0') {
                    return false;
                }
            } catch (e) {
                // Silently ignore storage errors (private mode, quota, etc).
            }

            return null;
        },
        saveNotifierState = function (isEnabled) {
            if (!isSoundPersistenceEnabled || !window.localStorage) {
                return;
            }

            try {
                window.localStorage.setItem(storageNotifierKey, isEnabled ? '1' : '0');
            } catch (e) {
                // Silently ignore storage errors (private mode, quota, etc).
            }
        },
        getSavedNotifierState = function () {
            if (!isSoundPersistenceEnabled || !window.localStorage) {
                return null;
            }

            try {
                let storedState = window.localStorage.getItem(storageNotifierKey);
                if (storedState === '1') {
                    return true;
                }
                if (storedState === '0') {
                    return false;
                }
            } catch (e) {
                // Silently ignore storage errors (private mode, quota, etc).
            }

            return null;
        },
        syncVolumeUIState = function (isEnabled) {
            let volumeController = $('.olistener-volume'),
                volumeIcon = volumeController.find('span.dashicons');

            volumeController.toggleClass('active', isEnabled);
            volumeIcon.removeClass('dashicons-controls-volumeon dashicons-controls-volumeoff');
            volumeIcon.addClass(isEnabled ? 'dashicons-controls-volumeon' : 'dashicons-controls-volumeoff');
        },
        playAlertSound = function () {
            if (!audioElement) {
                return;
            }

            let playPromise = audioElement.play();
            if (playPromise && typeof playPromise.catch === 'function') {
                playPromise.catch(function () {
                    // Browser can block autoplay when page is restored without user action.
                    pendingAlertPlayback = true;
                });
            }
        },
        unlockAudioOnInteraction = function () {
            if (!audioElement || audioUnlocked) {
                return;
            }

            let unlockHandler = function () {
                if (audioUnlocked) {
                    return;
                }

                let originalMutedState = audioElement.muted;
                audioElement.muted = true;
                let playPromise = audioElement.play();
                if (playPromise && typeof playPromise.then === 'function') {
                    playPromise.then(function () {
                        audioUnlocked = true;
                        audioElement.pause();
                        audioElement.currentTime = 0;
                        audioElement.muted = originalMutedState;

                        if (pendingAlertPlayback) {
                            pendingAlertPlayback = false;
                            playAlertSound();
                        }
                    }).catch(function () {
                        audioElement.muted = originalMutedState;
                        // Keep waiting for the next user interaction.
                    });
                }
            };

            $(document).on('click keydown touchstart', unlockHandler);
        },
        getUrlParameter = function getUrlParameter(sParam) {
            let sPageURL = window.location.search.substring(1),
                sURLVariables = sPageURL.split('&'),
                sParameterName,
                i;

            for (i = 0; i < sURLVariables.length; i++) {
                sParameterName = sURLVariables[i].split('=');

                if (sParameterName[0] === sParam) {
                    return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
                }
            }
            return false;
        };


    $(window).on('load hashchange', function () {

        let listenerBody = $('body'),
            listenerWrap = $('.olistener'),
            urlHash = window.location.hash.substr(1),
            urlHashResult = urlHash.split('&').reduce(function (res, item) {
                let parts = item.split('=');
                res[parts[0]] = parts[1];
                return res;
            }, {});

        if (listenerWrap.hasClass('olistener-active')) {
            return;
        }

        if ('olistener' === getUrlParameter('page') && ('notifier' === urlHashResult.tab || typeof urlHashResult.tab === 'undefined')) {
            listenerBody.addClass('olistener-bubble-active');
        } else {
            listenerBody.removeClass('olistener-bubble-active');
        }
    });

    $(document).on('ready', function () {

        let listenerWrap = $('.olistener'),
            audioSrc = listenerWrap.data('audio'),
            olistenerController = $('.olistener-action.olistener-controller'),
            volumeController = $('.olistener-volume'),
            ordersList = $('.olistener-orders'),
            olistenerPopup = $('.olistener-popup'),
            isNotifierUIPage = olistenerController.length > 0;

        audioElement = document.createElement('audio');

        if (typeof audioSrc !== 'undefined') {
            audioElement.setAttribute('src', audioSrc);
            audioElement.setAttribute("allow", "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture");
            unlockAudioOnInteraction();

            let savedSoundState = getSavedSoundState();
            let isSoundEnabled = savedSoundState;

            if (isSoundEnabled === null) {
                // Default to sound ON when no saved preference exists.
                isSoundEnabled = volumeController.length ? volumeController.hasClass('active') : true;
            }

            audioElement.muted = !isSoundEnabled;
            syncVolumeUIState(isSoundEnabled);

            let savedNotifierState = getSavedNotifierState();
            if (savedNotifierState === true && isNotifierUIPage) {
                let listenerBody = $('body'),
                    controllerIcon = olistenerController.find('span.dashicons');
                olistenerController.addClass('active');
                controllerIcon.removeClass('dashicons-controls-play').addClass('dashicons-controls-pause');
                listenerBody.removeClass('olistener-bubble-active');
                listenerWrap.addClass('olistener-active');
            }

            setInterval(function () {
                let isNotifierActive = isNotifierUIPage ? olistenerController.hasClass('active') : (savedNotifierState === true);
                if (isNotifierActive) {
                    $.ajax({
                        type: 'POST',
                        context: this,
                        url: pluginObject.ajaxUrl,
                        data: {
                            'action': 'olistener',
                        },
                        success: function (response) {
                            if (response.success && response.data.count > 0) {

                                let popupContent = response.data.htmlPopup;

                                ordersList.append(response.data.html);
                                // audioElement.load();
                                playAlertSound();

                                if (popupContent.length > 0) {
                                    olistenerPopup.find('.popup-content').html(popupContent);
                                    olistenerPopup.show();
                                }
                            }
                        },
                    });
                }

                if (ordersList.find('.olistener-row').length === 1) {
                    audioElement.pause();
                }
            }, pluginObject.interval);
        }

        audioElement.addEventListener('ended', function () {
            audioElement.currentTime = 0;
            playAlertSound();
        });
    });

    $(document).on('click', '.order-action.mark-read', function () {
        $(this).parent().parent().fadeOut().remove();
    });

    $(document).on('click', '.olistener-volume', function () {
        let volumeIsEnabled = !$(this).hasClass('active');
        audioElement.muted = !volumeIsEnabled;
        saveSoundState(volumeIsEnabled);
    });

    $(document).on('click', '.olistener-action', function () {

        let listenerBody = $('body'),
            controller = $(this),
            oListenerChecker = $('.olistener'),
            controllerClasses = controller.data('classes'),
            controllerIcon = controller.find('span.dashicons'),
            needToggle = true;

        if (typeof controllerClasses === 'undefined' || controllerClasses.length === 0) {
            needToggle = false;
        }

        if (needToggle) {
            controller.toggleClass('active');
            controllerIcon.toggleClass(controllerClasses);

            if (controllerIcon.hasClass('dashicons-controls-pause')) {
                listenerBody.removeClass('olistener-bubble-active');
                oListenerChecker.addClass('olistener-active');
                if (controller.hasClass('olistener-controller')) {
                    saveNotifierState(true);
                }
            } else if (controllerIcon.hasClass('dashicons-controls-play')) {
                listenerBody.addClass('olistener-bubble-active');
                oListenerChecker.removeClass('olistener-active');
                audioElement.pause();
                if (controller.hasClass('olistener-controller')) {
                    saveNotifierState(false);
                }
            }
            return;
        }

        if (!needToggle && confirm(pluginObject.confirmText)) {
            saveNotifierState(false);
            location.href = '';
        }
    });


    // Popup Skip button clicked
    $(document).on('click', '.olistener-popup .olistener-popup-box .popup-actions .popup-action.popup-action-skip', function (e) {
        $(this).parent().parent().parent().fadeOut();
    });

    // Popup Acknowledge button clicked
    $(document).on('click', '.olistener-popup .olistener-popup-box .popup-actions .popup-action.popup-action-ack', function (e) {
        e.preventDefault();
        pendingAlertPlayback = false;
        audioElement.pause();
        audioElement.currentTime = 0;
        $(this).parent().parent().parent().fadeOut();

        // $('.order-action.mark-read').trigger('click');
    })

    // $(document).on('wpsettings-attachment-loaded', function () {
    //     $('.pb_settings_form #submit').trigger('click');
    // });

    // $(document).on('wpsettings-attachment-removed', function (e, elRemoveButton) {
    //
    //     let elAttachmentContainer = elRemoveButton.parent();
    //
    //     elAttachmentContainer.find('input[type=hidden]').val('');
    //     elAttachmentContainer.find('.dashicons').css('opacity', 0);
    //     elRemoveButton.hide();
    //
    //     $('.pb_settings_form #submit').trigger('click');
    // });
})(jQuery, window, document, olistener);