( function($){
    "use strict";
    var prefix                    = 'gpls-wmfw-watermark-image-for-wordpress';
    var prefixUnderscored         = 'gpls_wmfw_watermark_image_for_wordpress';
    var localize_vars             = window[ prefixUnderscored + '_localize_vars' ];

    $(document).on( 'ready', (e) => {
        $('.' + localize_vars['classes_prefix'] + '-msgs-toast' ).toast({autohide: false});

        $(document).on( 'click', '.' + localize_vars['classes_prefix'] + '-msgs-toast .close-toast', (e) => {
            var $this = $(e.target);
            var toast = $this.parents('.toast').toast('hide');
        });

        // Auto hide the image cache busting url param.
        hideCacheBustingURLParam();

        // Restore Backup.
        $(document).on( 'click', '.' + localize_vars['classes_prefix'] + '-watermarks-options .restore-backup', (e) => {
            e.preventDefault();
            if ( confirm( localize_vars.labels.restore_backup_prompt ) ) {
                var backupOptionsBox = $('.' + localize_vars['classes_prefix'] + '-watermarks-options');
                backupOptionsBox.find('.action-btn').prop('disabled', true );
                backupOptionsBox.find('.loading').removeClass('d-none');
                var $this        = $(e.target);
                var attachmentID = $this.data('id');
                restoreBackup( attachmentID );
            }
        });

        // Delete Backup.
        $(document).on( 'click', '.' + localize_vars['classes_prefix'] + '-watermarks-options .delete-backup', (e) => {
            e.preventDefault();
            if ( confirm( localize_vars.labels.delete_backup_prompt ) ) {
                var backupOptionsBox = $('.' + localize_vars['classes_prefix'] + '-watermarks-options');
                backupOptionsBox.find('.action-btn').prop('disabled', true );
                backupOptionsBox.find('.loading').removeClass('d-none');
                var $this        = $(e.target);
                var attachmentID = $this.data('id');
                deleteBackup( attachmentID );
            }
        });
    });

    function deleteBackup( attachmentID ) {
        var backupOptionsBox = $('.' + localize_vars['classes_prefix'] + '-watermarks-options');
        var data             = {
            action: localize_vars.deleteOriginalImageBackupAction,
            nonce: localize_vars.nonce,
            attachmentID: attachmentID
        }
        $.ajax({
            method: 'POST',
            url: localize_vars.ajaxUrl,
            data,
            success: (resp) => {
                var status = ( resp['data']['result'] && 'success' === resp['data']['result'] ) ? 'bg-primary' : 'bg-danger';
                if ( resp['data']['msg'] ) {
                    showToast( resp['data']['msg'], status );
                }
                if ( resp['data']['errors'] ) {
                    showToast( resp['data']['errors'], 'bg-danger', true );
                }
                if ( resp['data']['result'] && 'success' === resp['data']['result'] ) {
                    backupOptionsBox.find('.backup-options').remove();
                }
            },
            error: (err) => {
                // console.log( 'error restoring backup', err );
                if ( err?.data?.message ) {
                    showToast( err.data.message, 'bg-danger' );
                }
            },
            complete: () => {
                backupOptionsBox.find('.action-btn').prop('disabled', false );
                backupOptionsBox.find('.loading').addClass('d-none');
            }
        });
    }

    function restoreBackup( attachmentID ) {
        var backupOptionsBox = $('.' + localize_vars['classes_prefix'] + '-watermarks-options');
        var checkedSizes     = [];
        $('.' + localize_vars['classes_prefix'] + '-restore-backup-image-size:checked').each( (index, element) => {
            var $this = $(element);
            checkedSizes.push( $this.val() );
        });
        var data             = {
            action: localize_vars.restoreOriginalImageBackupAction,
            nonce: localize_vars.nonce,
            attachmentID: attachmentID,
            sizes: checkedSizes
        }
        $.ajax({
            method: 'POST',
            url: localize_vars.ajaxUrl,
            data,
            success: (resp) => {
                var status = ( resp['data']['result'] && 'success' === resp['data']['result'] ) ? 'bg-primary' : 'bg-danger';
                if ( resp['data']['errors'] ) {
                    showToast( resp['data']['errors'], 'bg-danger', true );
                }
                if ( resp['data']['msg'] ) {
                    showToast( resp['data']['msg'], status );
                }
            },
            error: (err) => {
                // console.log( 'error restoring backup', err );
                if ( err?.data?.message ) {
                    showToast( err.data.message, 'bg-danger' );
                }
            },
            complete: () => {
                backupOptionsBox.find('.action-btn').prop('disabled', false );
                backupOptionsBox.find('.loading').addClass('d-none');
            }
        });
    }

    function showToast( toastMsg, bgColor = 'bg-primary', is_multiple = false ) {
        var toast = $('.' + localize_vars['classes_prefix'] + '-msgs-toast' );
        toast.removeClass( (index, className) => {
            return (className.match (/(^|\s)bg-\S+/g) || []).join(' ');
        });
        var html = '';
        if ( ! is_multiple ) {
            html = '<p>' + toastMsg + '</p>';
        } else {
            html = '<ul class="toast-notice-list">'
            toastMsg.forEach( ( msg ) => {
                html += '<li class="notice-item"><p>' + msg + '</p></li>';
            });
            html += '</ul>';
        }
        toast.addClass( bgColor ).find('.toast-body').html( html );
        toast.toast('show')
    }

    function hideCacheBustingURLParam() {
        var currentURL = new URL( window.location.href );
        if ( currentURL.searchParams.get( localize_vars.classes_prefix + '-force-img-refresh' ) ) {
            currentURL.searchParams.delete( localize_vars.classes_prefix + '-force-img-refresh' );
            window.history.replaceState( null, null, currentURL.href );
        }
    }

})(jQuery);
