jQuery(function ($) {
    window.f12_floating_menu_items_upload = window.f12_floating_menu_items_upload || {};
    /**
     * ReInit the upload fields
     */
    window.f12_floating_menu_items_upload.initUpload = function () {
        /**
         * This will init all upload windows.
         */
        $(document).find('.f12-floating-menu-image-upload').each(function () {
            if ($(this).attr('data-init') != 1) {
                $(this).wrap('<div class="f12-floating-menu-image-wrapper"><div class="f12-floating-menu-image-wrapper--inner"></div></div>');

                let label_html = '';
                let preview_html = '<div class="preview"></div>';

                if ($(this).attr('data-label').length > 0) {
                    label_html = '<div class="label"><label>' + $(this).attr('data-label') + '</label></div>';
                }

                $(this).before(
                    '<div class="image-options">' + preview_html + ' ' + label_html + '</div>'
                );

                if ($(this).attr('data-src').length > 0) {
                    $(this).parent().find('.preview').append('<img src="' + $(this).attr('data-src') + '" style="width:32px; height:32px;" />'); // TODO: Maybe replace the 32px with the settings size.
                }
                $(this).attr('data-init', 1);
            }
        });
    }

    /**
     * Change the layout of the image upload container
     * This will automatically use the data-url to parse the container
     * and display the required structure for the preview and upload button.
     */
    $(document).ready(function () {
        window.f12_floating_menu_items_upload.initUpload();
    });

    /**
     * Handle the icon upload for the links.
     * This will load and store the attachment id.
     */
    $(document).on('click', '.f12-floating-menu-image-upload', function (e) { /* on button click*/
        e.preventDefault();

        if (!$(this).attr('data-storage')) {
            throw 'Attribute "data-storage" is not defined. This id will tell the system where to store the attachment id of the selected image.';
        }

        if ($(document).find('#' + $(this).attr('data-storage')).length === 0) {
            throw 'Input field with id #' + $(this).attr('data-storage') + ' not found. This field is required to store the wordpress attachment id. Please add a input field e.g. <input id="' + $(this).attr('data-storage') + '" />';
        }

        if ($(this).parent().find('.preview').length === 0) {
            throw 'The preview container is missing. This container will normally be generated by the system. Please contact the plugin author for further support.';
        }

        var button = $(this),
            hiddenfieldstorage = $(this).attr('data-storage'),
            custom_uploader = wp.media({
                title: window.f12_floating_menu_items_upload.labels.wp_media_title, /* popup title */
                library: {type: 'image'},
                button: {text: window.f12_floating_menu_items_upload.labels.wp_media_button}, /* "Insert" button text */
                multiple: false
            }).on('select', function () {

                var attachments = custom_uploader.state().get('selection').map(function (a) {
                    a.toJSON();
                    return a;
                });

                /* add HTML element with an image */
                if (button.parent().find('.preview img').length > 0) {
                    button.parent().find('.preview img').attr('src', attachments[0].attributes.url);
                } else {
                    button.parent().find('.preview').append('<img src="' + attachments[0].attributes.url + '" style="width:32px; height:32px;" />'); // TODO: Maybe replace the 32px with the settings size.
                }

                /* add the IDs to the hidden field value */
                $('#' + hiddenfieldstorage).val(attachments[0].id).blur();
            }).open();
    });
});