import Vue from 'vue/dist/vue';
import EventBus from "../util/EventBus";
import EventTypes from "../util/EventTypes";
import MediaClient from "../api/MediaClient";
import ContextFactory from "../util/ContextFactory";


export default () => {
    return new Vue({
        delimiters: ['<<', '>>'],
        el: '#media-library-app',
        props: {},
        data: {},
        methods: {
            open: function (sourceEl, contextParams) {
                if (!contextParams.mediaTypes || contextParams.mediaTypes.length === 0) {
                    console.log('Error: no media types, cannot open library.');
                    return;
                }

                this.apiUrl = this.$el.getAttribute('data-api-url');
                MediaClient.setEndpoint(this.apiUrl);

                this.$refs.library.open(sourceEl, contextParams);
            },
            unlink: function (sourceEl) {
                let callerDomWrap = sourceEl.closest('.media-link-wrap');
                let previewWrap = callerDomWrap.querySelector(':scope .preview')
                if (previewWrap && !previewWrap.classList.contains('missing-media')) {
                    previewWrap.classList.add('missing-media');
                }

                [
                    callerDomWrap.querySelector(':scope .preview-wrap img'),
                    callerDomWrap.querySelector(':scope .preview-wrap .media-link'),
                    callerDomWrap.querySelector(':scope .preview-wrap .preview-el'),
                ].forEach((el) => el ? el.remove() : null)

                callerDomWrap.querySelector(':scope input[name$="[media_type]"]').value = '';
                callerDomWrap.querySelector(':scope input[name$="[media_pk]"]').value = '';
            },
        },
        mounted: function () {
            // this.context = ContextFactory.getDefaultValue()
        },
    });
}
