import InitLibraryButtons from "../../components/media_library/util/InitLibraryButtons";

const formType = 'aa-ft-linked-media';

function initPlugin(el, defaultOptions, libs) {
    var wrapClass = 'media-link-wrap';
    var formWrap = el.classList.contains(wrapClass) ? el : el.closest('.' + wrapClass);

    if (formWrap === null) {
        console.error('could not create file plugin');
        return;
    }

    var inputWrap = formWrap.querySelector(':scope .' + formType);
    if (inputWrap === null) {
        console.error('could not create file plugin (input wrap missing)');
        return;
    }
    var typeInput = inputWrap.querySelector('input[name$="[media_type]"]');
    var pkInput = inputWrap.querySelector('input[name$="[media_pk]"]');
    var mappingsInput = inputWrap.querySelector('input[name$="[mappings]"]');

    var createPlugin = function () {
        return {
            wrap: formWrap,
            typeInput: typeInput,
            pkInput: pkInput,
            mappingsInput: mappingsInput,
            init() {
                InitLibraryButtons(formWrap);
                const handler = (e) => {
                    if (e.srcElement && e.srcElement.classList.contains('media-link')) {
                        return;
                    }
                    e.preventDefault();

                    console.log(e);
                    let btn = this.wrap.querySelector('[data-action="open-library"]');
                    if (btn) {
                        btn.click();
                    }
                };
                formWrap.querySelector('.preview-wrap').addEventListener('click', handler.bind(this))

                // console.log('init linked media');
            },
        }
    };


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

    return plugin;
}

AAForm.addTypeHandler(formType, initPlugin);
