(function ($) {
    $.field_mediabrowser = function (element, options) {
        var defaults = {
            input_name: ""
        }
        var plugin = this;
        plugin.settings = {}
        var $element = $(element),
            element = element;
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            let input_name = plugin.settings.input_name;
            let multiple = plugin.settings.multiple;
            $element.find('.btn-browser-media').on('click', function (e) {
                if (this.window === undefined) {
                    this.window = wp.media({
                        title: 'Insert a media',
                        library: {type: 'image'},
                        multiple: multiple,
                        button: {text: 'Insert'}
                    });
                    var self = this;
                    this.window.on('select', function () {
                        var first = self.window.state().get('selection').first().toJSON();

                        $element.find(`input[name="${input_name}"]`).val(first.url);
                    });
                }
                this.window.open();
                return false;
            });
        }
        plugin.example_function = function () {
        };
        plugin.init();
    }

    $.fn.field_mediabrowser = function (options) {

        return this.each(function () {

            if (undefined == $(this).data('field_mediabrowser')) {
                var plugin = new $.field_mediabrowser(this, options);
                $(this).data('field_mediabrowser', plugin);
            }
        });
    }
})(jQuery);
