/* 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 Vue from 'vue';
import UIkit from 'uikit';
import api from '@yootheme/api';
import hooks from '@yootheme/hooks';
import essentials from 'essentials';
import { SourceExtended } from '@essentials/core/source';
import { FormPlaceholderDrop } from './components';

hooks.before('app.init', ({ extend }) => {
    extend({
        events: {
            prepareFields(e, fields) {
                if (!essentials.FormModel?.formNode) {
                    return;
                }

                for (const field of fields) {
                    if (!field.formPlaceholder) {
                        continue;
                    }

                    field.buttons = field.buttons || [];

                    field.buttons.push({
                        label: Vue.i18n.t('Placeholder'),
                        action: 'yooessentialsPickFormPlaceholder',
                    });
                }
            },
        },
    });
});

Vue.events.on('essentialsDynamicOptions', ({ result = [] }, { node, field }) => {
    if (!essentials?.FormModel?.formNode) {
        return result;
    }

    const Schema = api.builder.helpers.Schema;
    const query = { name: 'yooessentials_form_query' };
    const sourceField = Schema.findField(query.name);

    result.push({
        query,
        priority: 10,
        group: Vue.i18n.t('Submission'),
        name: 'yooessentials.form',
        title: 'Form',
        fields: SourceExtended.getFieldsList(sourceField),
        source: () => sourceField,
        match: ({ prop }) => prop?.query?.name === 'yooessentials_form_query',
        resolve: ({ name }) => {
            if (!field) {
                return { name, query };
            }

            SourceExtended.setExtendedProp(node, field.name, { name, query }, query);
        },
    });

    return result;
});

// remove unsupported queries (the ones not available during a form submissions)
Vue.events.on(
    'essentialsDynamicOptions',
    ({ result = [] }) => {
        if (!essentials?.FormModel?.formNode) {
            return result;
        }

        return result
            .filter((opt) => opt.group !== Vue.i18n.t('Inherit'))
            .filter((opt) => opt.group !== Vue.i18n.t('Page'));
    },
    -100
);

Vue.events.on('yooessentialsSourceQueryOrigin', ({ result }, { node, prop }) => {
    if (result) {
        return result;
    }

    prop = SourceExtended.getProp(node, prop);

    if (prop?.query?.name === 'yooessentials_form_query') {
        return 'yooessentials.form';
    }
});

Vue.events.on('yooessentialsPickFormPlaceholder', ({ origin }, field, { target }) => {
    const entries = essentials.FormModel.getFields()
        .filter((e) => e.props?.control_name)
        .map((e) => {
            const value = e.props.control_name;

            return {
                value,
                text: e.props?.control_label || value,
                meta: `{${value}}`,
            };
        });

    origin
        .$dropdown(FormPlaceholderDrop, { entries })
        .show(target, {
            classes: 'yo-dropdown',
            boundaryX: target.closest('.yo-sidebar-fields > *') || target,
        })
        .then((sel) => {
            if (!sel?.meta) {
                return;
            }

            if (!navigator.clipboard) {
                UIkit.notification({
                    message: 'Copying placeholder not supported, please input manually.',
                    status: 'danger',
                    timeout: 1500,
                });
                return;
            }

            navigator.clipboard.writeText(sel.meta);

            UIkit.notification({
                message: 'Placeholder copied to clipboard!',
                status: 'success',
                timeout: 1500,
            });

            // const fieldWrapper = parent(target);
            // const field = $('div.uk-margin-small > input', fieldWrapper) || $('div.uk-margin-small > textarea', fieldWrapper);

            // if (sel.meta) {
            //     field.value = `${field.value}${sel.meta}`;
            // }
        });
});

Vue.events.on('transformedNode', (e, newNode, node) => {
    if (
        node.children &&
        node.type.startsWith('yooessentials_form_') &&
        newNode.type.startsWith('yooessentials_form_') &&
        node.children.every((n) => n.type === 'yooessentials_form_option')
    ) {
        newNode.children = node.children;
    }
});
