<template>
    <div
        :class="{ 'uk-form-danger': !config }"
        class="uk-position-relative uk-input yo-input-iconnav-right uk-flex"
    >
        <img
            :uk-svg="`${assets}/images/builder/dynamic-field.svg`"
            class="uk-flex-none uk-margin-small-right"
        />

        <div v-if="!config" class="yo-input-locked uk-flex-1">
            {{ prop.name }}
        </div>

        <div v-else class="yo-input-locked uk-flex-1">
            <span v-if="prop.composed">
                {{ $t('Composed Source') }}
            </span>
            <span v-else>
                {{ breadcrumb.join(' - ') }}
            </span>
        </div>

        <div class="uk-position-center-right uk-position-small">
            <ul class="uk-iconnav uk-flex-nowrap">
                <li v-show="config">
                    <a
                        :title="$t('Edit')"
                        href
                        class="uk-icon-link uk-preserve-width"
                        uk-icon="pencil"
                        uk-tooltip="delay: 500"
                        @click.prevent="edit"
                    ></a>
                </li>
                <li v-show="config && !prop.composed">
                    <a
                        :title="$t('Compose')"
                        href
                        class="uk-icon-link uk-preserve-width"
                        uk-icon="forward"
                        uk-tooltip="delay: 500"
                        @click.prevent="migrateToComposable"
                    ></a>
                </li>
                <li v-if="!field.source_default">
                    <a
                        :title="$t('Delete')"
                        href
                        class="uk-icon-link uk-preserve-width"
                        uk-icon="trash"
                        uk-tooltip="delay: 500"
                        @click.prevent="remove"
                    ></a>
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
import api from '@yootheme/api';
import SourceExtended from '../../../source/SourceExtended';
import DynamicFieldDropdown from './DynamicFieldDropdown.vue';
import { isFunction } from 'uikit-util';

export default {
    name: 'DynamicField',

    inject: ['$node'],

    provide() {
        return {
            prop: this.prop,
        };
    },

    props: {
        field: {
            type: Object,
            required: true,
        },
        values: Object,
    },

    computed: {
        prop() {
            return SourceExtended.getProp(this.$node, this.field.name) || {};
        },

        dynamicOptions() {
            return SourceExtended.getDynamicOptions({
                node: this.$node,
                field: this.field,
            });
        },

        matchedOption() {
            return this.dynamicOptions.find((opt) => opt.match({ prop: this.prop }));
        },

        // returns prop field
        config() {
            const { Schema } = api.builder.helpers;

            if (!this.matchedOption) {
                return null;
            }

            if (this.prop?.composed) {
                return this.prop.composed;
            }

            const fields =
                this.matchedOption.fields ||
                Schema.getFields(this.matchedOption.source({ prop: this.prop }));

            const propField = fields.find((field) => field.value === this.prop?.name);

            if (!propField) {
                return null;
            }

            return SourceExtended.resolvePropFieldsets(propField);
        },

        breadcrumb() {
            const { Source } = api.builder.helpers;
            const SourceField = Source.getSourceField(SourceExtended.path(this.$node, this.prop));

            return [
                this.isList ? `[ ${this.config.text} ]` : this.config.text,
                this.isMultiSource ? `[ ${this.config.group} ]` : this.config.group,
                this.matchedOption?.crumb || SourceField?.metadata?.group,
            ].filter(Boolean);
        },

        isMultiSource() {
            if (this.matchedOption?.group === 'Inherit') {
                return false;
            }

            const sourceField = this.matchedOption?.source({ prop: this.prop });

            const isMulti = sourceField?.type?.kind === 'LIST';
            const isAdjacent = SourceExtended.isAdjacent(this.$node);
            const isFieldSource = this.$node.source_extended?.props?.[this.field.name];

            return Boolean(isMulti && (isAdjacent || isFieldSource));
        },

        isList() {
            return this.config.type === 'LIST';
        },
    },

    created() {
        this.assets = api.config.assets;
    },

    methods: {
        edit() {
            if (isFunction(this.matchedOption.edit)) {
                this.matchedOption.edit({ prop: this.prop });
                return;
            }

            this.$dropdown(DynamicFieldDropdown, {
                prop: this.prop,
                fields: this.config.fieldsets,
                isMulti: this.isMultiSource || this.isList,
            }).show(this.$el);
        },

        migrateToComposable() {
            const composedOption = this.dynamicOptions.find(({ name }) => name === 'composable');
            const prop = composedOption.migrate(this.prop);

            SourceExtended.setExtendedProp(this.$node, this.field.name, prop);

            composedOption.edit({ prop });
        },

        remove() {
            SourceExtended.removeProp(this.$node, this.field.name);
        },
    },
};
</script>
