const formType = 'aa-image';
function initPlugin(el, defaultOptions, libs) {
    var formWrap = el.classList.contains(formType) ? el : el.closest('.aa-image');
    if (formWrap === null) {
        console.error('could not create image plugin');
        return;
    }
    var fileInput = formWrap.querySelector(':scope .custom-file-input');
    var previewWrap = formWrap.querySelector(':scope .preview');
    var createPlugin = function () {
        return {
            wrap: formWrap,
            previewWrap: previewWrap,
            fileInput: fileInput,
            init() {
                this.fileInput.addEventListener('change', plugin.fileInputChangeListener.bind(this));
            },
            fileInputChangeListener(e) {
                var input = e.target;
                input.nextElementSibling.innerText = input.files[0].name;
                var img = this.wrap.querySelector(':scope .preview-wrap img');
                if (img) {
                    this._loadURL(img, input);
                    if (previewWrap.classList.contains('missing-media')) {
                        previewWrap.classList.remove('missing-media')
                    }
                }
            },
            _loadURL(img, input) {
                if (input.files && input.files[0]) {
                    img.src = '';

                    var reader = new FileReader();
                    reader.onload = function (e) {
                        img.src = e.target.result;
                    }
                    reader.readAsDataURL(input.files[0]); // convert to base64 string
                }
            }
        }
    };


    var plugin = createPlugin();
    plugin.init();

    return plugin;
}

AAForm.addTypeHandler(formType, initPlugin);
