
export default {

    name: 'pages-tree',

    data() {
        return {
            loading: false,
            actionItem: null
        }
    },

    props: {
        modelValue: {
            type: Array,
            default: []
        },
        level: {
            type: Number,
            default: 0
        },
        locale: {
            type: String,
            default: 'default'
        },
        siteSettings: {
            type: Object,
            default: {}
        },
        p: {
            type: Object,
            default: null
        }
    },

    watch: {
        actionItem(val) {

            if (val) {
                setTimeout(() => {
                    document.getElementById('popout-pages-tree-context-menu').show();
                }, 50);
            }
        }
    },

    computed: {
        pages: {
            get() {
                return this.modelValue || []
            },
            set(value) {
                this.$emit('update:modelValue', value)
            }
        }
    },


    mounted() {

        if (this.p && this.p._children) {

            this.loading = true;

            let params = {_pid:this.p._id};

            if (this.locale && this.loacale !== 'default') {
                params.locale = this.locale;
            }

            this.$request('/pages/load', params).then(pages => {

                this.p.children = pages;
                this.loading = false;
            }).catch(res => {
                this.loading = false;
                App.ui.notify(res.error || 'Loading children failed!', 'error');
            });
        }
    },

    methods: {

        lstUpdate() {
            if (this.p) {
                this.p._children = this.p.children.length;
                this.p._showChildren = true;
            }
        },

        change(evt) {

            const { data, from, to, oldIndex, newIndex } = evt;

            setTimeout(() => {

                let pId = to.closest('[data-page-id]')?.getAttribute('data-page-id')  || null;
                let toUpdate = {}

                data._pid = pId;

                [...to.children].forEach((child, idx) => {

                    let page = {_id: child.getAttribute('data-page-id'), _o: idx};

                    if (page._id === data._id) {
                        page._pid = pId;
                        page._o = newIndex;
                    }

                    toUpdate[page._id] = page;
                });

                [...from.children].forEach((child, idx) => {
                    let page = {_id: child.getAttribute('data-page-id'), _o: idx};

                    if (!toUpdate[page._id]) {
                        toUpdate[page._id] = page;
                    }
                });

                toUpdate = Object.values(toUpdate);

                if (toUpdate.length) {
                    this.$request('/pages/utils/updateOrder', {pages:toUpdate})
                }

            }, 0);

        },

        remove(page) {
            App.ui.confirm('Are you sure?', () => {

                this.$request('/pages/remove', {page}).then(res => {
                    this.pages.splice(this.pages.indexOf(page), 1);
                }).catch(res => {
                    App.ui.notify(res.error || 'Page removing failed!', 'error');
                });
            });
        },

        createPage(pid = null) {
            VueView.ui.offcanvas('pages:assets/dialogs/choose-pagetype.js', {pid});
        },


        moveItem(item, pos) {

            if (!pos || this.pages.length < 2) return;

            if (pos === 'first') {
                this.pages.unshift(this.pages.splice(this.pages.indexOf(item), 1)[0]);
            }

            if (pos === 'last') {
                this.pages.push(this.pages.splice(this.pages.indexOf(item), 1)[0])
            }

            let toUpdate = []

            this.pages.forEach((p, idx) => {
                toUpdate.push({_id: p._id, _o: idx});
            });

            this.$request('/pages/utils/updateOrder', {pages:toUpdate});
        },

        toggleActionItemActions(item, tree) {

            if (!tree) {
                tree = this;
            }

            if (this.p) {
                this.$emit('show-item-actions', item, tree);
                return;
            }

            let val =  (!item || this.actionItem?.item === item) ? null : {tree, item};

            this.actionItem = val;
        }
    },

    template: /*html*/`
        <div>
            <app-loader size="small" v-if="loading"></app-loader>

            <vue-draggable
                v-model="pages"
                handle=".fm-handle"
                class="pages-tree-dragarea"
                :group="'pages'"
                :swapThreshold="0.35"
                :animation="100"
                @end="change"
                @add="lstUpdate"
                @remove="lstUpdate"
                v-if="!loading"
            >
                <div class="kiss-margin-xsmall" :key="element._id" v-for="(element, idx) in pages" :data-page-id="element._id" :data-page-idx="idx">
                    <kiss-card class="kiss-padding-small kiss-flex kiss-flex-middle kiss-margin-xsmall" gap="small" theme="bordered contrast shadowed">
                        <a class="fm-handle kiss-color-muted kiss-cursor-grab"><icon>drag_handle</icon></a>
                        <a class="kiss-color-muted" :class="{'kiss-hidden': !element._children}" :placeholder="t('Toggle children')" @click="element._showChildren = !element._showChildren">
                            <icon>{{ element._showChildren ? 'indeterminate_check_box' : 'add_box' }}</icon>
                        </a>
                        <div>
                            <icon :class="{'kiss-color-danger': !element._state, 'kiss-color-success': element._state === 1}" v-if="!element._state || locale == 'default'">circle</icon>
                            <icon class="kiss-color-danger" v-else-if="siteSettings.locales[locale] === false">cloud_off</icon>
                            <icon class="kiss-color-danger" v-else-if="element._locales && element._locales[locale] === false">circle</icon>
                            <icon :class="{'kiss-color-danger': !element._state, 'kiss-color-success': element._state === 1}" v-else>circle</icon>
                        </div>
                        <div v-if="level === 0 && idx === 0" title="Homepage"><icon class="kiss-color-primary" size="larger">home</icon></div>
                        <div class="kiss-flex-1 kiss-size-small kiss-text-truncate kiss-visible-toggle">

                            <a class="kiss-link-muted" :href="$routeUrl('/pages/page/'+element._id)" :class="{'kiss-text-bold': element._children, 'kiss-text-bold kiss-color-primary':level === 0 && idx === 0}">
                                {{ element.title }}
                            </a>

                            <span class="kiss-badge kiss-margin-small-start kiss-text-upper kiss-invisible-hover">{{ element.type }}</span>
                        </div>
                        <a @click="toggleActionItemActions(element)"><icon>more_horiz</icon></a>
                    </kiss-card>
                    <div v-if="element._showChildren || !element._children" :style="{paddingLeft: (((level+1)*23)+'px')}">
                        <pages-tree class="pages-tree" v-model="element.children" :level="level+1" :p="element" :locale="locale" :site-settings="siteSettings" @show-item-actions="(item, tree) => toggleActionItemActions(item, tree)"></pages-tree>
                    </div>
                </div>

            </vue-draggable>
        </div>
        <teleport to="body" v-if="!p && actionItem">
            <kiss-popout id="popout-pages-tree-context-menu" @popoutclose="toggleActionItemActions(null)">
                <kiss-content>
                    <kiss-navlist class="kiss-margin">
                        <ul>
                            <li class="kiss-nav-header">{{ t('Page actions') }}</li>
                            <li v-if="actionAsset">
                                <div class="kiss-color-muted kiss-text-truncate kiss-margin-small-bottom">{{ t('Item actions')}}</div>
                            </li>
                            <li>
                                <a class="kiss-flex kiss-flex-middle" :href="$routeUrl('/pages/page/'+actionItem.item._id)">
                                    <icon class="kiss-margin-small-end" size="larger">create</icon>
                                    {{ t('Edit') }}
                                </a>
                            </li>
                            <li>
                                <a class="kiss-flex kiss-flex-middle" @click="createPage(actionItem.item._id)">
                                    <icon class="kiss-margin-small-end" size="larger">create_new_folder</icon>
                                    {{ t('Add child page') }}
                                </a>
                            </li>
                            <li class="kiss-nav-divider"></li>
                            <li>
                                <a class="kiss-flex kiss-flex-middle" :href="$routeUrl('/pages/clone/'+actionItem.item._id)">
                                    <icon class="kiss-margin-small-end" size="larger">control_point_duplicate</icon>
                                    {{ t('Clone') }}
                                </a>
                            </li>
                            <li class="kiss-nav-divider"></li>
                            <li>
                                <a class="kiss-flex kiss-flex-middle kiss-color-danger"  @click="actionItem.tree.remove(actionItem.item)">
                                    <icon class="kiss-margin-small-end" size="larger">delete</icon>
                                    {{ t('Delete') }}
                                </a>
                            </li>
                        </ul>
                        <ul class="kiss-margin-small" v-if="Array.isArray(actionItem.tree.pages) && actionItem.tree.pages.length > 1">
                            <li class="kiss-nav-header">{{ t('Move page') }}</li>
                            <li v-if="actionItem.tree.pages.indexOf(actionItem.item) !== 0">
                                <a class="kiss-flex kiss-flex-middle" @click="actionItem.tree.moveItem(actionItem.item, 'first')">
                                        <icon class="kiss-margin-small-end">arrow_upward</icon>
                                        {{ t('Move first') }}
                                    </a>
                                </li>
                            <li v-if="actionItem.tree.pages.indexOf(actionItem.item) !== actionItem.tree.pages.length - 1">
                                <a class="kiss-flex kiss-flex-middle" @click="actionItem.tree.moveItem(actionItem.item, 'last')">
                                    <icon class="kiss-margin-small-end">arrow_downward</icon>
                                    {{ t('Move last') }}
                                </a>
                            </li>
                        </ul>
                        </kiss-navlist>
                </kiss-content>
            </kiss-popout>
        </teleport>
    `
}
