import { h } from "@stencil/core";
import { debounce } from '../../utils/debounce';
import { validator } from '../../utils/validator';
export const getInputCreator = (component, onerror) => {
    let error = '';
    const fc = (_, children) => {
        const props = getProps();
        return [
            props.label != undefined && (h("bce-label", { disabled: props.disabled, hasFocus: props.hasFocus, tooltip: props.tooltip, "data-hover": props.hover }, props.label)),
            children,
            (error || props.info) && h("small", null, error || props.info)
        ];
    };
    const getProps = () => ({
        el: component.el,
        disabled: component.disabled,
        hasFocus: component.hasFocus,
        hover: component.hover,
        label: component.label,
        tooltip: component.tooltip,
        validation: component.validation,
        info: component.info
    });
    const handleInput = () => {
        if (error)
            validate();
        else
            _debounceValidate();
    };
    const reset = () => {
        error = '';
        if (onerror)
            onerror(error);
    };
    const validate = async (silent = false) => {
        const props = getProps();
        if (!props.validation)
            return [];
        const label = props.label || '';
        const name = props.name || '';
        const meta = { label, name };
        const errors = await validator.validate(props.validation, props.el, meta);
        if (!silent && onerror) {
            error = errors.length ? errors[0].message : '';
            onerror(error);
        }
        return errors;
    };
    const _debounceValidate = debounce(validate, 1000);
    return Object.assign(fc, { getProps, handleInput, reset, validate });
};
