import React from "react";
import { isIntegerType, isNumberType } from "../schema";
import { LimeElementsWidgetAdapter } from "../adapters";
import { Slider } from "./slider";
export class InputField extends React.Component {
    constructor(props) {
        super(props);
        this.props = props;
        this.handleChange = this.handleChange.bind(this);
    }
    render() {
        const props = this.props;
        if (isRange(props.schema)) {
            return React.createElement(Slider, props);
        }
        const type = getInputType(props.schema);
        const step = getStepSize(props.schema);
        const additionalProps = getAdditionalProps(props.schema);
        return React.createElement(LimeElementsWidgetAdapter, {
            name: 'limel-input-field',
            value: props.value,
            events: {
                change: this.handleChange,
            },
            widgetProps: props,
            extraProps: Object.assign({ step: step, type: type }, additionalProps),
        });
    }
    handleChange(event) {
        event.stopPropagation();
        const props = this.props;
        const type = getInputType(props.schema);
        if (!props.onChange) {
            return;
        }
        let value;
        if (event.detail || typeof event.detail === 'number') {
            value = event.detail;
        }
        else if (type === 'number') {
            value = null;
        }
        else {
            value = props.required ? null : '';
        }
        props.onChange(value);
    }
}
function getInputType(schema) {
    if (isNumberType(schema) || isIntegerType(schema)) {
        return 'number';
    }
    if (schema.format === 'email') {
        return 'email';
    }
    return 'text';
}
function getStepSize(schema) {
    if (isNumberType(schema) && schema.multipleOf) {
        return +schema.multipleOf || 'any';
    }
    if (isIntegerType(schema)) {
        return Math.floor(+schema.multipleOf) || 1;
    }
    return 'any';
}
function getAdditionalProps(schema) {
    var _a, _b;
    let props = {};
    if (schema.minimum) {
        props.min = schema.minimum;
    }
    if (schema.maximum) {
        props.max = schema.maximum;
    }
    if (schema.maxLength) {
        props.maxlength = schema.maxLength;
    }
    if (schema.minLength) {
        props.minlength = schema.minLength;
    }
    if ((_b = (_a = schema.lime) === null || _a === void 0 ? void 0 : _a.component) === null || _b === void 0 ? void 0 : _b.props) {
        props = Object.assign(Object.assign({}, props), schema.lime.component.props);
    }
    return props;
}
function isRange(schema) {
    if (!isNumberType(schema) && !isIntegerType(schema)) {
        return false;
    }
    return 'minimum' in schema && 'maximum' in schema && 'multipleOf' in schema;
}
