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";
import {triggerFlashNotification} from "../../flashbag_notification";
import InitLibraryButtons from "../util/InitLibraryButtons";

Vue.component('library', {
    data: function () {
        return {
            context: ContextFactory.getContextConfig(),
            isReady: false,
            visible: false,
            loading: false,
            uploadPanelVisible: false,
            items: {
                type: Array,
                default: function () {
                    return []
                }
            },
            ignoreEscapeSignal: false,
        };
    },
    methods: {
        show: function () {
            this.visible = true;
            document.body.style.overflow = 'hidden';
        },
        hide: function () {
            this.visible = false;
            document.body.style.overflow = '';
        },
        reset: function () {
            let data = {};
            const defaultVal = ContextFactory.getDefaultValue();
            Object.keys(defaultVal)
                .forEach((key) => data[key] = defaultVal[key])
            this.context = {
                ...this.context,
                ...data,
            }
            this.isReady = false;
            this.visible = false;
            this.loading = false;
            this.uploadPanelVisible = false;
            this.ignoreEscapeSignal = false;
        },
        open: function (sourceEl, contextParams) {
            console.log('Library open');
            console.log(contextParams);
            this.reset();
            this.context.sourceEl = sourceEl;
            Object.keys(contextParams).forEach((k) => {
                this.context[k] = contextParams[k];
            })
            this.show();
            this.loadItems();
        },
        loadItems: function () {
            this.show();
            this.loading = true;
            MediaClient
                .fetchItems(this.context.mediaTypes, this.context.page, this.context.searchTerm)
                .then((data) => {
                    let copyData = [
                        "items",
                        "page",
                        "maxPage",
                        "count",
                        "maxUploadSize",
                        "maxUploadSizeReadable",
                        "mediaTypesConfig",
                    ];
                    let passedData = {}
                    copyData.forEach(key => passedData[key] = data[key]);
                    this.context = {
                        ...this.context,
                        ...passedData,
                    }
                    this.loading = false;
                    this.isReady = true;
                });
        },
        search: function (payload) {
            console.log('search');
            console.log(payload);
            this.context = {
                ...this.context,
                ...{
                    searchTerm: payload.searchTerm,
                    page: 1,
                },
            };

            console.log('search with:', this.context.searchTerm);
            this.loadItems()
        },
        goToPage: function (page) {
            page = parseInt(page);
            console.log('console.log(page)');
            console.log(page);
            if (page && page <= this.context.maxPage && page >= 1) {
                console.log('changepage + load');
                this.context.page = page
                this.loadItems();
            }
        },
        uploadPaneVisibility: function (state) {
            this.uploadPanelVisible = state;
        },
        _escapeCallback: function (e) {
            if (this.ignoreEscapeSignal) {
                return
            }
            const isInput = el => /^(?:input|select|textarea)$/i.test(el?.nodeName);
            if (isInput(e.target)) {
                return
            }

            if (e.key === "Escape") {
                this.hide();
            }
        },
        _bindEscape: function () {
            window.addEventListener('keyup', this._escapeCallback);
        },
        _unbindEscape: function () {
            window.removeEventListener('keyup', this._escapeCallback);
        },
        mediaSelect: function (payload) {
            console.log('Library choseItem');
            console.log(payload);
            MediaClient.mediaPreview(payload.type, payload.media.id).then((data) => {
                if (data.status) {
                    let callerDomWrap = this.context.sourceEl.closest('.media-link-wrap');
                    if (data.preview) {
                        let previewWrap = callerDomWrap.querySelector(':scope .preview-outer');
                        previewWrap.innerHTML = data.preview;
                        InitLibraryButtons(callerDomWrap);// re-init library open behavior after html replacing
                    }
                    callerDomWrap.querySelector(':scope input[name$="[media_type]"]').value = payload.type;
                    callerDomWrap.querySelector(':scope input[name$="[media_pk]"]').value = payload.media.id;

                    this.hide();
                }
                if (data.successes) {
                    data.successes.forEach((msg) => triggerFlashNotification('success', msg))
                }
            })
        },
        mediaDelete: function (payload) {
            console.log('Library delete');
            console.log(payload);
            let name = payload?.media?.fileName;
            if (name) {
                name = '"' + name + '"'
            }
            let confirmed = confirm('Confirmer la suppression de ' + name + ' ?')
            this.ignoreEscapeSignal = true;// conflicting with confirm modal, so shut down during this process
            if (confirmed) {
                MediaClient.deleteMedia(payload.type, payload.media.id).then((data) => {
                    if (data.status) {
                        if (data.successes) {
                            data.successes.forEach((msg) => triggerFlashNotification('success', msg))
                        }
                        this.loadItems();

                    }
                    this.ignoreEscapeSignal = false;
                })
            }
        },
    },
    mounted() {
        this._bindEscape();

        EventBus.$on(EventTypes.LIBRARY_OPEN, this.loadItems);
        EventBus.$on(EventTypes.MEDIA_SELECT, this.mediaSelect);
        EventBus.$on(EventTypes.MEDIA_DELETE, this.mediaDelete);
        EventBus.$on(EventTypes.LIBRARY_SEARCH, this.search);
        EventBus.$on(EventTypes.LIBRARY_UPLOAD_PANE, this.uploadPaneVisibility);
        EventBus.$on(EventTypes.LIBRARY_GO_TO_PAGE, this.goToPage);
    },
    beforeUnmount() {
        this._unbindEscape();
    },
    template: `
        <div v-if="isReady">
            <div class="library-wrap"
                 :class="{'opened': context?.mediaTypes?.length > 0 && this.visible}"
            >

                <div class="title-bar">
                    <h1 class="title">Bibliothèque media</h1>
                    <button class="close-btn btn btn-primary"
                            @click="hide()"
                    >
                        <i class="fa fa-close"></i>
                    </button>
                </div>
                <div class="library-content">
                    <div class="library-actions" v-if="!uploadPanelVisible">
                        <div class="container">
                            <div class="row">
                                <div class="col">
                                    <library-upload-btn/>
                                    <div class="counter">{{ context.count }} items</div>
                                </div>
                                <div class="col">
                                    <library-search :context="context" :input-val="context.searchTerm"/>
                                    <library-pagination :context="context"/>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div v-if="loading" class="aa-loader-wrap" v-html="this.context.loader"/>

                    <library-upload v-if="!loading && uploadPanelVisible"
                                    :context="context"
                    />
                    <media-listing v-else-if="!loading"
                                   :media-items="items"
                                   :context="context"
                    />
                </div>
            </div>
            <div class="library-backdrop"></div>
        </div>
    `
});
