"use strict";
(function ($) {
    $.field_gallery = function (element, options) {
        var defaults = {
            input_name: "",
            name_field_deleted: "",
            list_image_deleted: [],
            enable_upload: false,
            multiple: false
        }
        var plugin = this;
        plugin.settings = {}
        var $element = $(element), 
            element = element;
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $element.find('.list-image').sortable({
                cancel: '.upload'
            });
            $element.find('.list-image .image-item').on('click', function (e) {
                let $self_image = $(this);
                $.confirm({
                    title: 'Confirm',
                    content: 'Are you sure delete this image in gallery ?',
                    buttons: {
                        confirm: function () {
                            let id = $self_image.data('id');
                            if (id) {
                                plugin.settings.list_image_deleted.push(id);
                                $(`input[name="${plugin.settings.name_field_deleted['0']}"]`).val(JSON.stringify(plugin.settings.list_image_deleted));
                            }
                            $self_image.remove();
                        },
                        cancel: function () {
                        }
                    }
                });
            });
            let enable_upload = plugin.settings.enable_upload;
            let multiple = plugin.settings.multiple;
            if (enable_upload) {
                $element.find('.list-image .upload').on('click',function (e) {
                    $element.find('input[type="file"].upload').trigger('click');
                });
                $element.find('input[type="file"].upload').change(function () {
                    plugin.readURL(this);
                });
            } else {
                $element.find('.list-image .upload').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();
                            let $last_element = $element.find('.list-image .ui-sortable-handle:last');
                            let $image = $(`<li class="image-item" ><i class="far fa-trash-alt remove"></i><img class="image" src="${first.url}"><input type="hidden" class="item-image" name="${plugin.settings.input_name}[]" value="${first.url}"></li>`);
                            $image.insertBefore($last_element);
                            $element.find('.list-image').sortable('refresh');
                        });
                    }
                    this.window.open();
                    return false;
                });
            }
        };
        plugin.format_name_input_file = function () {
            let $list_input = $element.find('.list-image input.item-image');
            $list_input.each(function (index, item) {
                $(this).attr('name', `${plugin.settings.input_name}[${index}]`);
            });
        };
        plugin.example_function = function () {
        };
        plugin.readURL = function (input) {
            let $file_input = $(input);
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    let $image = $(`<li class="image-item" ><i class="far fa-trash-alt remove"></i><img class="image" src="${e.target.result}"></li>`);
                    let $last_element = $element.find('.list-image .ui-sortable-handle:last');
                    $image.insertBefore($last_element);
                    $element.find('.list-image').sortable('refresh');
                    $image.append($file_input);
                    $file_input.removeClass('upload');
                    $file_input.attr('name', `${plugin.settings.input_name}[]`);
                    let $new_input = $('<input type="file"  class="upload item-image"  />');
                    $new_input.appendTo($element);
                    $new_input.change(function () {
                        plugin.readURL(this);
                    });
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
        plugin.init();
    }
    
    $.fn.field_gallery = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('field_gallery')) {
                var plugin = new $.field_gallery(this, options);
                $(this).data('field_gallery', plugin);
            }
        });
    }
})(jQuery);