<template>
    <div v-if="isEmpty(value)" class="uk-margin">
        <div>{{ $t('No rules yet.') }}</div>

        <button
            class="uk-button uk-button-default uk-margin-top"
            type="button"
            @click.prevent="add"
        >
            {{ $t('Add Rule') }}
        </button>
    </div>

    <div v-else class="uk-margin uk-visible-toggle">
        <ul
            v-sortable="{ group: 'dataset-items', enabled: isSortable }"
            :class="[
                'uk-nav uk-nav-default yo-sidebar-marginless yo-nav-sortable uk-margin uk-margin-remove-bottom',
                { 'yo-nav-iconnav': !attributes.disabled },
            ]"
            cls-custom="yo-nav-sortable-drag"
        >
            <ResourceListItem
                v-for="{ item, disabled, ...props } in items"
                :key="item.id"
                v-bind="props"
                :disabled="Boolean(attributes.disabled || disabled)"
                @edit="edit(item)"
                @copy="copy(item)"
                @delete="remove(item)"
            />
        </ul>

        <hr class="uk-margin-remove" />

        <div class="uk-flex uk-flex-between uk-margin-small-top">
            <div>
                <button
                    type="button"
                    class="uk-button uk-button-small uk-button-default"
                    @click.prevent="add"
                >
                    {{ $t('Add Rule') }}
                </button>
            </div>

            <div class="uk-invisible-hover">
                <a
                    v-if="logs"
                    :title="$t('Evaluation Logs')"
                    class="uk-icon-link"
                    uk-icon="ye--report"
                    uk-tooltip="delay: 500"
                    @click="showLogs(logs)"
                ></a>
            </div>
        </div>
    </div>
</template>

<script>
import essentials from '../api';
import FieldYooessentialsField from './DatasetMultiField.vue';

export default {
    name: 'ConditionRulesField',

    idPrefix: 'ci_',

    extends: FieldYooessentialsField,

    inject: {
        $node: {},
        Condition: {
            from: 'EssentialsCondition',
        },
        Logs: {
            from: 'EssentialsLogs',
        },
    },

    computed: {
        logs: {
            get() {
                const { access } = this.Logs.logs;
                const nodeId = essentials.Builder.id(this.$node);

                const logs = access?.[nodeId];

                // associate logs with rules by it id,
                // a fallback for rules created with older versions
                logs?.entries?.forEach((log, i) => {
                    log.id = log.id || this.value[i]?.id;
                });

                return logs;
            },
            cache: false,
        },

        items() {
            return this.value.map((item, i) => {
                const rule = this.options[item.type];
                const props = item?.props || {};
                const title = props.name || 'Rule';
                const meta = `{${++i}} ${rule?.title}`;

                // get all node logs for the rule
                const logs = this.logs?.entries?.some(({ id }) => id === item.id);

                return {
                    item,
                    title,
                    meta,
                    error: !rule ? `Unknown Rule Type: ${item.type}` : '',
                    disabled: !rule,
                    icon: rule?.icon,
                    description: rule?.description,
                    actions: [
                        logs && {
                            title: 'Evaluation Logs',
                            icon: 'ye--report',
                            callback: () => {
                                this.showRuleLogs(item, logs);
                            },
                        },
                        this.isCopyable && rule ? 'copy' : null,
                        this.isDeletale !== false ? 'delete' : null,
                    ].filter(Boolean),
                };
            });
        },
    },

    methods: {
        initOptions() {
            const rules = this.Condition.rules;

            for (const name in rules) {
                const rule = rules[name];
                this.options[name] = {
                    ...rule,
                    panel: this.getPanel({ ...rule.panel }),
                };
            }
        },

        showLogs() {
            this.$modal(essentials.components.LogReportModal, {
                title: this.$t('Evaluation Log'),
                logs: {
                    message: `Evaluated as <span class="uk-text-bold">${this.logs.result}</span>.`,
                },
            }).show();
        },

        showRuleLogs(rule) {
            const index = this.value.findIndex(({ id }) => id === rule.id) + 1;
            const ruleType = this.Condition.rules[rule.type];

            const logs = this.logs.entries
                .filter(({ id }) => id === rule.id)
                .map((log) => ({
                    ...log,
                    args: log.props,
                    message: `Evaluated as <span class="uk-text-bold">${log.result}</span> with the following arguments:`,
                }));

            this.$modal(essentials.components.LogReportModal, {
                title: this.$t('Evaluation Logs'),
                subtitle: `{${index}} ${ruleType.title}`,
                logs,
            }).show();
        },
    },
};
</script>
