<script>
import DatasetField from './DatasetField.vue';
import { DynamicPanel } from '../source';
import { get, keyBy, uuid } from '../util';
import { ResourcePicker } from '../components';

export default {
    name: 'DatasetMultiField',

    extends: DatasetField,

    data: () => ({
        options: {},
    }),

    computed: {
        items() {
            return this.value.map((item) => {
                const option = this.options[item.type];

                return {
                    item,
                    id: uuid(),
                    title: this.getTitle(item, option),
                    meta: this.getMeta(item, option),
                    error: !option ? `Unknown Type: ${item.type}` : '',
                    disabled: !option || item.props?.status === 'disabled',
                    icon: option?.icon,
                    description: option?.description,
                    actions: [this.isCopyable && option ? 'copy' : null, this.isDeletale !== false ? 'delete' : null],
                };
            });
        },
    },

    created() {
        this.initOptions();
    },

    methods: {
        initOptions() {
            const options = this.field?.options.map((opt) => ({
                ...opt,
                panel: this.getPanel(opt.panel),
            }));

            this.options = keyBy(options, 'name');
        },

        add() {
            this.$modal(ResourcePicker, {
                items: Object.values(this.options),
            })
                .show({ container: true })
                .then((option) => {
                    if (!option) {
                        return;
                    }

                    const item = {
                        type: option.name,
                        ...(option.defaults || {}),
                    };

                    this.push(item);
                    this.edit(item);
                });
        },

        edit(item) {
            if (!item.props) {
                this.$set(item, 'props', {});
            }

            const option = this.options[item.type];

            this.openPanel({
                title: this.getTitle(item, option),
                name: 'dataset-multi-panel',
                ...option.panel,
                component: DynamicPanel,
                props: {
                    node: item,
                    values: item.props,
                },
            });
        },

        getTitle(item, option) {
            return get(item, option?.titleMap || 'props.name') || option?.titleFallback;
        },

        getMeta(item, option) {
            return get(item, option?.metaMap || 'meta') || option?.metaFallback;
        },
    },
};
</script>
