(function($){
    $.widget('ui.dialog_modal', {
        _instance: null,
        instance: function (value){
            if(value === undefined){
              return this._instance
          }
        },
        _create: function (){
            const { options = {} } = this;
            const {
                closeAction = null,
                addBodyClass = null,
                addMainWrapperClass = null,
                css = null,
                passedArgs = []
            } = options;
            const body = $('body');
            const width = body.innerWidth;
            body.css("overflow", "hidden");
            body.width(width);
            this.element.remove();
            const dialog = bootbox.dialog(...passedArgs);
            dialog.on('hidden', function () {
                const body = $('body');
                body.css("overflow", "auto");
                body.width('auto');
                if (closeAction && typeof closeAction === 'function') {
                    closeAction();
                }
                return true;
            });
            if (addBodyClass){
                dialog.find('.modal-body').addClass(addBodyClass);
            }
            if (addMainWrapperClass){
                dialog.addClass(addMainWrapperClass);
            }
            if (css){
                dialog.css(css);
            }
            this._instance = dialog;
            const outsideClickListener = (event) => {
                const widgetOverlay = document.querySelector('.ui-widget-overlay');
                const selector = '.bootbox.modal'
                const $target = $(event.target);
                // do not close if a modal is not found or not visible, or a widget overlay is presented.
                // what happens when from the modal was opened another widget (e.g., class finder)
                // otherwise, manipulation inside the child widget will cause the parent modal to close.
                if (!$target.closest(selector).length && $(selector).is(':visible') && !widgetOverlay) {
                    dialog.modal('hide');
                    document.removeEventListener('click', outsideClickListener);
                }
            }
            document.addEventListener('click', outsideClickListener, true)
        }
    })
    $.extend($.ui.modal, {
        instances: []
    });
})(jQuery);
