<template>
    <DropdownList
        max-height="large"
        :entries="fieldsList"
        :selected="selection"
        :search.sync="search"
        @resolve="({ value }) => $emit('resolve', { name: value })"
    >
        <template #nav>
            <div class="uk-flex uk-flex-right uk-flex-middle">
                <span class="uk-text-meta uk-disabled">{{ title }}</span>
                <a v-if="!selection" class="uk-margin-left" @click.prevent="$emit('config')">
                    <span uk-icon="more-vertical" class="uk-icon-link"></span>
                </a>
            </div>
        </template>
    </DropdownList>
</template>

<script>
import { DropdownList } from '../../../components';

export default {
    name: 'SourceFields',

    components: {
        DropdownList,
    },

    props: {
        fields: {
            type: Array,
            required: true,
        },
        selection: {
            type: String,
        },
    },

    data: () => ({
        search: '',
    }),

    computed: {
        title() {
            return this.source?.metadata.label;
        },
        fieldsList() {
            return this.fields
                .filter(({ text }) => {
                    const value = [text].map((v) => v?.toString().toLowerCase()).join(' ');

                    return !this.search || ~value.indexOf(this.search.toLowerCase());
                })
                .map(({ es_field_meta, ...rest }) => ({
                    ...rest,
                    meta: es_field_meta,
                }));
        },
    },
};
</script>
