/* 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 essentials from 'essentials';
import { FormAreaIcon } from './components';

Vue.events.on('statusesNode', ({ origin: Node, result = [] }) => {
    if (isInvalidField(Node)) {
        result.push('error');
    }

    return result;
});

Vue.events.on('statusIconsNode', ({ origin: Node, result = [] }) => {
    if (hasFormaAreaIcon(Node)) {
        result.push({ component: FormAreaIcon });
    }

    return result;
});

function isInvalidField(Node) {
    const { node } = Node;

    return essentials.FormModel.isInvalidField(node);
}

function hasFormaAreaIcon(Node) {
    if (isInvalidField(Node)) {
        return true;
    }

    const nodes = [];

    if (Node.type.name === 'section') {
        nodes.push(Node.node);
    } else if (Node.type.name === 'row') {
        nodes.push(...Node.children);
    }

    return nodes.some((node) => Boolean(node.props?.yooessentials_form?.state));
}
