/* Essentials YOOtheme Pro 2.2.16 build 0813.1608; ZOOlanders https://www.zoolanders.com; Copyright (C) Joolanders, SL; http://www.gnu.org/licenses/gpl.html GNU/GPL */

import essentials from 'essentials';
import { uuid } from '@essentials/core/util';

export default {
    name: 'SourceDynamic',

    created() {
        essentials.SourceDynamic = this;
    },

    computed: {
        queries: {
            get() {
                return essentials.Config.get('dynamic.queries', []);
            },

            set(values) {
                essentials.Config.set('dynamic.queries', values);
            },
        },
    },

    methods: {
        isGlobalQuery(id) {
            return Boolean(this.getGlobalQuery(id));
        },

        getGlobalQuery(id) {
            return this.queries.find((q) => q.id === id);
        },

        saveGlobalQuery(values) {
            const queries = [...this.queries];

            if (values.id) {
                queries[queries.findIndex(({ id }) => id === values.id)] = values;
            } else {
                values = {
                    ...values,
                    id: uuid(),
                    created_at: Date.now(),
                    created_on: essentials.version,
                };

                queries.push(values);
            }

            this.queries = queries;

            return values;
        },

        removeGlobalQuery(query) {
            const queries = [...this.queries];
            queries.splice(queries.indexOf(query), 1);

            this.queries = queries;
        },
    },
};
