import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useRef } from 'react';
import formatDate from 'date-fns/format';
import endOfToday from 'date-fns/endOfToday';
import { FormError } from './Error';
import { useFormChildrenContext } from './context';
var TimeFormat = 'HH:mm:ss';
export function isViewDrivenProps(props) {
    return !!props.name;
}
export var ValidateOccasion;
(function (ValidateOccasion) {
    ValidateOccasion[ValidateOccasion["None"] = 0] = "None";
    ValidateOccasion[ValidateOccasion["Change"] = 1] = "Change";
    ValidateOccasion[ValidateOccasion["Blur"] = 2] = "Blur";
    ValidateOccasion[ValidateOccasion["Default"] = 3] = "Default";
})(ValidateOccasion || (ValidateOccasion = {}));
export var TouchWhen;
(function (TouchWhen) {
    TouchWhen[TouchWhen["Change"] = 0] = "Change";
    TouchWhen[TouchWhen["Blur"] = 1] = "Blur";
})(TouchWhen || (TouchWhen = {}));
export function dateDefaultValueFactory() {
    return new Date();
}
export function dateRangeDefaultValueFactory() {
    return [new Date(), new Date()];
}
export function dateDefaultTimeFactory() {
    return formatDate(new Date(), TimeFormat);
}
export function dateRangeDefaultTimeFactory() {
    return [
        formatDate(new Date(), TimeFormat),
        formatDate(endOfToday(), TimeFormat),
    ];
}
export function defaultRenderError(error) {
    if (error == null) {
        return null;
    }
    return _jsx(FormError, { children: error.message }, void 0);
}
export function useFormChild(model, scrollAnchorRef) {
    var ctx = useFormChildrenContext();
    var posRef = useRef(ctx.children.length);
    useEffect(function () {
        var formChild = {
            valid: function () {
                return model.valid();
            },
            getDOMNode: function () {
                return scrollAnchorRef && scrollAnchorRef.current;
            },
        };
        if (posRef.current < ctx.children.length) {
            ctx.children.splice(posRef.current, 0, formChild);
        }
        else {
            posRef.current = ctx.children.length;
            ctx.children.push(formChild);
        }
        return function () {
            var pos = ctx.children.indexOf(formChild);
            if (pos !== -1) {
                posRef.current = pos;
                ctx.children.splice(pos, 1);
            }
        };
    }, [model, scrollAnchorRef, ctx]);
}
