/* 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 api from '@yootheme/api';
import hooks from '@yootheme/hooks';
import fields from '@yootheme/fields';
import { SourceExtended } from '@essentials/core/source';

// workaround for the extended component not available right away
hooks.after('app.init', () => {
    const { FieldYooessentialsSourceSelect, FieldSourceSelect } = fields.components;

    FieldYooessentialsSourceSelect.extends = FieldSourceSelect;
});

export default {
    name: 'SourceSelect',

    // extends: FieldSourceSelect

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

    computed: {
        value: {
            get() {
                return api.builder.helpers.Source.getQuery(this.$node);
            },

            set(name) {
                SourceExtended.setQuery(this.$node, name);
            },
        },

        globalFields() {
            return this.SourceDynamic.queries.map(({ id, name }) => ({
                value: SourceExtended.globalQueryKey(id),
                text: name,
                group: this.labels.Global,
            }));
        },

        labels() {
            return {
                Page: this.$t('Page'),
                Parent: this.$t('Parent'),
                Global: this.$t('Global'),
            };
        },
    },

    methods: {
        filterOptions() {
            const { FieldSourceSelect } = fields.components;

            const options = FieldSourceSelect.methods.filterOptions.call(this);
            const orphan = options.filter((opt) => opt.group === '');
            const omittedGroups = this.field.omitgroups || [];

            const Parent = options.find((opt) => opt.label === this.labels.Parent);
            const Page = options.find((opt) => opt.label === this.labels.Page);
            const Global = options.find((opt) => opt.label === this.labels.Global) || {
                label: this.labels.Global,
                options: [],
            };

            Global.options = [...Global.options, ...orphan, ...this.globalFields];

            return [
                { text: this.$t('None'), value: '' },
                Parent,
                Page,
                Global,
                ...options
                    .filter((opt) => opt.label && opt.label !== this.labels.Parent)
                    .filter((opt) => opt.label && opt.label !== this.labels.Page)
                    .filter((opt) => opt.label && opt.label !== this.labels.Global),
            ]
                .filter(Boolean)
                .filter((opt) => !omittedGroups.includes(this.labels[opt?.label]));
        },
    },
};
