<template>
    <div v-if="!queryObject">{{ $t('Query Not Found') }}</div>

    <SourcePanel v-else :node="queryObject" :panel="panel" :values="queryObject" />
</template>

<script>
import api from '@yootheme/api';
import SourcePanel from './SourcePanel';

export default {
    name: 'QueryPanel',

    components: { SourcePanel },

    inject: {
        Sidebar: {},
        SourceDynamic: {
            from: 'EssentialsSourceDynamic',
        },
    },

    props: {
        queryId: {
            type: String,
            required: true,
        },
    },

    computed: {
        queryObject() {
            return this.SourceDynamic.getGlobalQuery(this.queryId);
        },

        panel() {
            return api.customizer.panels['yooessentials-source-query-global'] || {};
        },
    },

    created() {
        const stop = this.SourceDynamic.$watch('queries', () => {
            if (!this.SourceDynamic.getGlobalQuery(this.queryId) && this.Sidebar?.closePanel) {
                this.Sidebar.closePanel();
            }

            stop();
        });
    },

    events: {
        openPanel: {
            handler({ params }) {
                params[0].component = SourcePanel;
            },

            priority: 5,
        },

        'yooessentials-prerequest'({ params }) {
            const form = params?.[0]?.form ?? {};

            params[0].form = { ...form, ...this.Sidebar?.panel?.props?.values };
        },
    },
};
</script>
