import { useMemo, useState, useEffect } from 'react';
import noop from '../../../utils/noop';
import { getFieldSetChildChangeObservable } from './set';
export function useModelFromContext(ctx, name, model, check) {
    var parent = (ctx !== null && ctx !== void 0 ? ctx : {}).parent;
    var m = useMemo(function () {
        if (typeof name === 'string') {
            var m_1 = parent.get(name);
            if (check(m_1)) {
                return m_1;
            }
        }
        if (check(model)) {
            return model;
        }
        return null;
    }, [name, model, check, parent]);
    var _a = useState(m), maybeModel = _a[0], setModel = _a[1];
    useEffect(function () {
        if (!name) {
            return noop;
        }
        var m = parent.get(name);
        check(m) && setModel(m);
        var $ = getFieldSetChildChangeObservable(parent, name).subscribe(function (name) {
            var candidate = parent.get(name);
            if (check(candidate)) {
                setModel(candidate);
            }
        });
        return function () { return $.unsubscribe(); };
    }, [name, parent, m, check]);
    return maybeModel;
}
