(function (app) {
    'use strict';

    const u = app.modules.util;

    function findByPath(root, path) {
        if (!path || path === '') {
            return root;
        }
        const segs = u.ptrParse(path);
        let cur = root;
        for (let i = 0; i < segs.length; i++) {
            if (!cur || typeof cur.child !== 'function') {
                return null;
            }
            cur = cur.child(segs[i]);
        }
        return cur || null;
    }

    function apply(errors) {
        if (!errors || !errors.length || !app.rootWidget) {
            return;
        }
        for (let i = 0; i < errors.length; i++) {
            const err = errors[i];
            const widget = findByPath(app.rootWidget, err.path || '');
            if (widget && typeof widget.setError === 'function') {
                widget.setError(err.message || 'Invalid value');
            }
        }
    }

    function clear() {
        if (app.rootWidget) {
            app.rootWidget.clearErrors();
        }
    }

    app.modules.errors = { apply: apply, clear: clear };
})(window.formApp);
