import { convertToDate, getDateFormValue } from '../../../calendar/helpers.js';
import { asNumber } from '../../util.js';
export function createFormValueState(host, config) {
    return new FormValue(host, config);
}
const defaultTransformers = {
    setValue: (value) => value || '',
    getValue: (value) => value,
    setDefaultValue: (value) => value || '',
    getDefaultValue: (value) => value,
    setFormValue: (value, _) => value || null,
};
export const defaultBooleanTransformers = {
    setValue: Boolean,
    setDefaultValue: Boolean,
    setFormValue: (checked, host) => {
        return checked && 'value' in host ? host.value || 'on' : null;
    },
};
export const defaultNumberTransformers = {
    setValue: asNumber,
    setDefaultValue: asNumber,
    setFormValue: (value) => value.toString(),
};
export const defaultDateTimeTransformers = {
    setValue: convertToDate,
    setDefaultValue: convertToDate,
    setFormValue: getDateFormValue,
};
export const defaultFileListTransformer = {
    setValue: (value) => value || null,
    getValue: (value) => value,
    setDefaultValue: (value) => value || null,
    getDefaultValue: (value) => value,
    setFormValue: (files, host) => {
        if (!host.name || !files) {
            return null;
        }
        const data = new FormData();
        for (const file of Array.from(files)) {
            data.append(host.name, file);
        }
        return data;
    },
};
export class FormValue {
    constructor(host, config) {
        this._host = host;
        this._value = config.initialValue;
        this._defaultValue = config.initialDefaultValue ?? this._value;
        this._setFormValue = host[FormValue.setFormValueKey];
        this._transformers = {
            ...defaultTransformers,
            ...config.transformers,
        };
    }
    setValueAndFormState(value) {
        this.value = value;
        this._setFormValue.call(this._host, this._transformers.setFormValue(this.value, this._host));
    }
    set defaultValue(value) {
        this._defaultValue = this._transformers.setDefaultValue(value);
    }
    get defaultValue() {
        return this._transformers.getDefaultValue(this._defaultValue);
    }
    set value(value) {
        this._value = this._transformers.setValue(value);
    }
    get value() {
        return this._transformers.getValue(this._value);
    }
}
FormValue.setFormValueKey = '_setFormValue';
//# sourceMappingURL=form-value.js.map