let instanceCount = 0;

export default {

    _meta: {
        label: 'Collection page items',
        info: 'Content items with page routes',
        icon: 'pages:assets/icons/collectionpageitems.svg',
        settings: [
            {name: 'collection', type: 'options-linkModel', info: 'Page type collection source'},
            {name: 'display', type: 'text'},
        ]
    },

    data() {

        let val = this.modelValue || {
            'pages:field': 'collectionpageitems',
            mode: 'dynamic',
            items: []
        };

        // legacy fix - remove later
        if (!val['pages:field']) {
            val['pages:field'] = 'collectionpageitems';
        }

        return {
            uid: `field-collecionpageitems-${++instanceCount}`,
            val,
            loading: true,
            pages: [],
        }
    },

    props: {
        modelValue: {
            type: Object,
            default: null
        },
        collection: {
            type: String,
            default: null
        },
        display: {
            type: String,
            default: null
        },
        limit: {
            type: Number,
            default: null
        },
        pickItems: {
            type: Boolean,
            default: false
        },
    },

    mounted() {

        let options = {
            filter: { type: 'collection'}
        };

        if (this.collection) {
            options.filter['data.collection'] = this.collection;
        }

        App.request('/pages/utils/find', {options}).then(pages => {
            this.pages = pages.items;
            this.loading = false;
        });
    },

    computed: {

        mode() {
            return this.val?.mode || 'dynamic';
        },

        page() {

            if (!this.val || !this.val.pageCollectionId) {
                return null;
            }

            return this.pages.find(p => p._id == this.val.pageCollectionId) || null;
        },

        pickItemsOptions() {

            let filter = null;

            if (this.page.data.filter) {

                filter = this.page.data.filter;

                if (typeof(filter) === 'string') {
                    try {
                        filter = JSON5.parse(filter)
                    } catch(e) {
                        filter = null;
                    }
                }
            }

            return  [
                {
                    name: 'items',
                    type: 'contentItemLink',
                    multiple: true,
                    label: 'Selected items',
                    opts: {
                        link: this.page.data.collection,
                        display: this.display || null,
                        default: [],
                        filter
                    }
                }
            ]
        }
    },

    watch: {
        val: {
            handler() { this.update() },
            deep: true
        },
        modelValue(val) {
            this.val = this.modelValue || {items:[]};
        }
    },

    methods: {
        update() {
            this.$emit('update:modelValue', this.val ? this.val || {} : null)
        }
    },

    template: /*html*/`
        <div field="collectionpageitems">

            <app-loader size="small" v-if="loading"></app-loader>

            <div v-if="!loading">

                <kiss-card class="kiss-padding-small kiss-size-small kiss-position-relative kiss-margin-small kiss-overlay-input kiss-display-block" theme="bordered contrast">
                    <div class="kiss-size-xsmall kiss-margin-small">{{ t('Source') }}</div>
                    <div class="kiss-color-muted" v-if="!pages.length">{{ t('No collection pages available') }}</div>
                    <div class="kiss-color-muted" v-if="pages.length && !page">{{ t('Select a collection page ...') }}</div>
                    <div class="kiss-margin-xsmall" v-if="page">
                        <div class="kiss-text-bold">{{ page.title }}</div>
                        <div class="kiss-color-muted kiss-size-xsmall">{{ page._r }}</div>
                    </div>
                    <select v-model="val.pageCollectionId" v-if="pages.length">
                        <option :value="null"></option>
                        <option v-for="p in pages" :value="p._id">{{ p.title }}</option>
                    </select>
                </kiss-card>

                <div class="kiss-padding-large kiss-color-muted kiss-align-center kiss-text-caption" v-if="!page">
                    {{ t('Please select a collection page') }}
                </div>

                <div class="kiss-margin" v-if="page">
                    <div class="kiss-size-xsmall kiss-color-muted kiss-margin-small-bottom">{{ t('Mode') }}</div>
                    <div class="kiss-button-group">
                        <button type="button" class="kiss-button kiss-button-small" :class="{'kiss-button-primary': mode == 'dynamic'}" @click="val.mode = 'dynamic'">{{ t('Dynamic') }}</button>
                        <button type="button" class="kiss-button kiss-button-small" :class="{'kiss-button-primary': mode == 'selected'}" @click="val.mode = 'selected'">{{ t('Selected') }}</button>
                    </div>
                </div>

                <div v-if="page && mode == 'dynamic'">

                    <div class="kiss-margin-small">
                        <div class="kiss-size-xsmall kiss-text-bold">{{ t('Items filter') }}</div>
                        <div class="kiss-color-muted kiss-size-xsmall kiss-margin-small-bottom">{{ t('Items filter JSON') }}</div>
                        <field-object v-model="val.filter" :height="100" :asString="true"></field-object>
                    </div>

                    <div class="kiss-margin-small" v-if="!val.items.length">
                        <div class="kiss-size-xsmall kiss-color-muted kiss-margin-small-bottom">{{ t('Limit') }}</div>
                        <field-number v-model="val.limit" placeholder="10"></field-number>
                    </div>
                </div>

                <div class="kiss-margin-small" v-if="page && mode == 'selected'">
                    <fields-renderer v-model="val" :fields="pickItemsOptions"></fields-renderer>
                </div>

            </div>
        </div>
    `
}
