"use strict";
exports.__esModule = true;
exports.TextField = exports.TextFieldRender = exports.cnTextField = exports.COMPONENT_NAME = void 0;
var tslib_1 = require("tslib");
require("./TextField.css");
var react_1 = (0, tslib_1.__importStar)(require("react"));
var react_textarea_autosize_1 = (0, tslib_1.__importDefault)(require("react-textarea-autosize"));
var useForkRef_1 = require("../../hooks/useForkRef/useForkRef");
var IconClose_1 = require("../../icons/IconClose/IconClose");
var IconSelect_1 = require("../../icons/IconSelect/IconSelect");
var IconSelectOpen_1 = require("../../icons/IconSelectOpen/IconSelectOpen");
var bem_1 = require("../../utils/bem");
var getSizeByMap_1 = require("../../utils/getSizeByMap");
var usePropsHandler_1 = require("../EventInterceptor/usePropsHandler");
var FieldCaption_1 = require("../FieldCaption/FieldCaption");
var FieldLabel_1 = require("../FieldLabel/FieldLabel");
var helpers_1 = require("./helpers");
exports.COMPONENT_NAME = 'TextField';
exports.cnTextField = (0, bem_1.cn)(exports.COMPONENT_NAME);
function TextFieldRender(props, ref) {
    var textFieldRef = react_1["default"].useRef(null);
    var inputRef = react_1["default"].useRef(null);
    var _a = (0, usePropsHandler_1.usePropsHandler)(exports.COMPONENT_NAME, props, textFieldRef), className = _a.className, _b = _a.type, type = _b === void 0 ? 'text' : _b, value = _a.value, onChange = _a.onChange, id = _a.id, name = _a.name, rows = _a.rows, cols = _a.cols, minRows = _a.minRows, maxRows = _a.maxRows, inputRefProp = _a.inputRef, maxLength = _a.maxLength, disabled = _a.disabled, _c = _a.size, size = _c === void 0 ? helpers_1.textFieldPropSizeDefault : _c, _d = _a.view, view = _d === void 0 ? helpers_1.textFieldPropViewDefault : _d, _e = _a.form, form = _e === void 0 ? helpers_1.textFieldPropFormDefault : _e, state = _a.state, status = _a.status, _f = _a.width, width = _f === void 0 ? helpers_1.textFieldPropWidthDefault : _f, onBlur = _a.onBlur, onFocus = _a.onFocus, _g = _a.autoFocus, autoFocus = _g === void 0 ? false : _g, placeholder = _a.placeholder, leftSide = _a.leftSide, rightSide = _a.rightSide, autoComplete = _a.autoComplete, withClearButton = _a.withClearButton, max = _a.max, min = _a.min, readOnly = _a.readOnly, required = _a.required, _h = _a.step, step = _h === void 0 ? 1 : _h, tabIndex = _a.tabIndex, ariaLabel = _a.ariaLabel, label = _a.label, _j = _a.labelPosition, labelPosition = _j === void 0 ? 'top' : _j, caption = _a.caption, iconSizeProp = _a.iconSize, focused = _a.focused, component = _a.component, otherProps = (0, tslib_1.__rest)(_a, ["className", "type", "value", "onChange", "id", "name", "rows", "cols", "minRows", "maxRows", "inputRef", "maxLength", "disabled", "size", "view", "form", "state", "status", "width", "onBlur", "onFocus", "autoFocus", "placeholder", "leftSide", "rightSide", "autoComplete", "withClearButton", "max", "min", "readOnly", "required", "step", "tabIndex", "ariaLabel", "label", "labelPosition", "caption", "iconSize", "focused", "component"]);
    var _k = (0, tslib_1.__read)((0, react_1.useState)(autoFocus), 2), focus = _k[0], setFocus = _k[1];
    var textarea = type === 'textarea';
    var LeftIcon = leftSide;
    var RightIcon = rightSide;
    var leftSideIsString = typeof leftSide === 'string';
    var rightSideIsString = typeof rightSide === 'string';
    var iconSize = (0, getSizeByMap_1.getSizeByMap)(helpers_1.sizeMap, size, iconSizeProp);
    var handleChange = function (e) {
        var value = e.target.value;
        !disabled && (onChange === null || onChange === void 0 ? void 0 : onChange({ e: e, id: id, name: name, value: value || null }));
    };
    var handleBlur = function (e) {
        setFocus(false);
        onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
    };
    var handleFocus = function (e) {
        setFocus(true);
        onFocus === null || onFocus === void 0 ? void 0 : onFocus(e);
    };
    var commonProps = {
        'className': (0, exports.cnTextField)('Input'),
        'value': value || '',
        'onChange': handleChange,
        // onChange: onChange,
        maxLength: maxLength,
        disabled: disabled,
        'onBlur': handleBlur,
        'onFocus': handleFocus,
        autoFocus: autoFocus,
        placeholder: placeholder,
        autoComplete: autoComplete,
        readOnly: readOnly,
        // required,
        tabIndex: tabIndex,
        name: name,
        'id': id ? id.toString() : '',
        'aria-label': ariaLabel
    };
    var textareaProps = {
        rows: rows,
        cols: cols,
        minRows: minRows || rows,
        maxRows: maxRows || rows,
        inputRef: (0, useForkRef_1.useForkRef)([inputRef, inputRefProp])
    };
    var inputProps = {
        type: type,
        max: max,
        min: min,
        step: step,
        ref: (0, useForkRef_1.useForkRef)([inputRef, inputRefProp])
    };
    var handleClear = function (e) {
        var _a;
        onChange === null || onChange === void 0 ? void 0 : onChange({
            e: e,
            value: ''
        });
        (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
    };
    var changeNumberValue = function (e, isIncrement) {
        var _a;
        if (isIncrement === void 0) { isIncrement = true; }
        var currentValue = value || 0;
        currentValue = isIncrement
            ? Number(currentValue) + Number(step)
            : Number(currentValue) - Number(step);
        onChange === null || onChange === void 0 ? void 0 : onChange({
            e: e,
            value: currentValue.toFixed(Number(
            /* Необходимо для того чтобы избежать ситуации, когда по нажатию
            на кнопку прибавляется число с погрешностью.
            Здесь мы берем разрядность дробной части шага и ограничиваем
            результирующее число этой разрядностью */
            (_a = Number(step)
                .toString()
                .split('.')[1]) === null || _a === void 0 ? void 0 : _a.length) || 0)
        });
    };
    return (react_1["default"].createElement("div", (0, tslib_1.__assign)({ className: (0, exports.cnTextField)({ labelPosition: labelPosition, size: size, view: view, width: width }, [className]) }, otherProps),
        label && (react_1["default"].createElement(FieldLabel_1.FieldLabel, { required: required, className: (0, exports.cnTextField)('Label', { labelPosition: labelPosition }), size: (0, getSizeByMap_1.getSizeByMap)(helpers_1.sizeMap, size) }, label)),
        react_1["default"].createElement("div", { className: (0, exports.cnTextField)('Body') },
            react_1["default"].createElement("div", { className: (0, exports.cnTextField)('InputContainer', {
                    view: view,
                    form: form,
                    status: status || state,
                    disabled: disabled,
                    type: type,
                    focus: focus || focused,
                    withValue: !!value
                }), ref: (0, useForkRef_1.useForkRef)([ref, textFieldRef]) },
                LeftIcon && (react_1["default"].createElement("div", { className: (0, exports.cnTextField)('Side', {
                        position: 'left',
                        type: leftSideIsString ? 'string' : 'icon'
                    }), title: typeof leftSide === 'string' ? leftSide : undefined }, leftSideIsString ? (leftSide) : (react_1["default"].createElement(LeftIcon, { className: (0, exports.cnTextField)('Icon'), size: iconSize })))),
                textarea ? (react_1["default"].createElement(react_textarea_autosize_1["default"], (0, tslib_1.__assign)({}, commonProps, textareaProps))) : (react_1["default"].createElement("input", (0, tslib_1.__assign)({}, commonProps, inputProps))),
                type === 'number' && (react_1["default"].createElement("div", { className: (0, exports.cnTextField)('Counter') },
                    react_1["default"].createElement("button", { onClick: function (e) { return changeNumberValue(e, true); }, type: "button", className: (0, exports.cnTextField)('CounterButton') },
                        react_1["default"].createElement(IconSelectOpen_1.IconSelectOpen, { size: "xs" })),
                    react_1["default"].createElement("button", { onClick: function (e) { return changeNumberValue(e, false); }, type: "button", className: (0, exports.cnTextField)('CounterButton') },
                        react_1["default"].createElement(IconSelect_1.IconSelect, { size: "xs" })))),
                value && withClearButton && type !== 'number' && (react_1["default"].createElement("button", { type: "button", disabled: disabled, onClick: handleClear, className: (0, exports.cnTextField)('ClearButton') },
                    react_1["default"].createElement(IconClose_1.IconClose, { size: "xs", className: (0, exports.cnTextField)('ClearButtonIcon') }))),
                RightIcon && type !== 'number' && (react_1["default"].createElement("div", { className: (0, exports.cnTextField)('Side', {
                        position: 'right',
                        type: rightSideIsString ? 'string' : 'icon'
                    }), title: typeof rightSide === 'string' ? rightSide : undefined }, rightSideIsString ? (rightSide) : (react_1["default"].createElement(RightIcon, { className: (0, exports.cnTextField)('Icon'), size: iconSize }))))),
            caption && (react_1["default"].createElement(FieldCaption_1.FieldCaption, { className: (0, exports.cnTextField)('Caption'), status: status || state }, caption)))));
}
exports.TextFieldRender = TextFieldRender;
exports.TextField = (0, react_1.forwardRef)(TextFieldRender);
(0, tslib_1.__exportStar)(require("./helpers"), exports);
