import MediaLibraryInstance from "./MediaLibraryInstance";

export default function InitLibraryButtons(wrap) {
    if (document.querySelector('#media-library-app')) {

        const btns = wrap.querySelectorAll('[data-action="open-library"]')
        btns.forEach((el) => {
            const handler = (e) => {
                // keep links proper behavior, open library for all other tags clicked
                if (e.target && e.target.tagName.toLowerCase() === 'a') {
                    return;
                }
                e.preventDefault();

                const mediaTypesStr = el.getAttribute('data-action-payload');
                MediaLibraryInstance().open(el, {
                    mediaTypes: mediaTypesStr.split(',')
                });
            };
            el.addEventListener('click', handler);
            const prev = wrap.querySelector('.preview-outer .preview');
            if (prev) {
                prev.addEventListener('click', handler);
            }
        });
        const unlinkBtns = wrap.querySelectorAll('[data-action="library-unlink"]')
        unlinkBtns.forEach((el) => {
            el.addEventListener('click', (e) => {
                e.preventDefault();
                MediaLibraryInstance().unlink(el);
            });
        });
    }
}
