"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "NumberInput", {
    enumerable: true,
    get: function() {
        return NumberInput;
    }
});
var _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
var _utils = require("../../../../utils");
var _hooks = require("../../../../hooks");
var _constants = require("../../../../utils/constants");
var _utils1 = require("../../utils");
var _NumberInputtokens = require("../../NumberInput.tokens");
var _Inputstyles = require("./Input.styles");
function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
var NumberInput = /*#__PURE__*/ (0, _react.forwardRef)(function(_0, _1) {
    var _ref = [
        _0,
        _1
    ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), value = _ref2.value, precision = _ref2.precision, min = _ref2.min, max = _ref2.max, isLoading = _ref2.isLoading, loader = _ref2.loader, disabled = _ref2.disabled, segmentation = _ref2.segmentation, textBefore = _ref2.textBefore, textAfter = _ref2.textAfter, isManualInput = _ref2.isManualInput, isInputFocused = _ref2.isInputFocused, setIsInputFocused = _ref2.setIsInputFocused, setIsAnimationRun = _ref2.setIsAnimationRun, setInnerValue = _ref2.setInnerValue, onChange = _ref2.onChange, onBlur = _ref2.onBlur, onKeyDown = _ref2.onKeyDown, rest = _object_without_properties(_ref2, [
        "value",
        "precision",
        "min",
        "max",
        "isLoading",
        "loader",
        "disabled",
        "segmentation",
        "textBefore",
        "textAfter",
        "isManualInput",
        "isInputFocused",
        "setIsInputFocused",
        "setIsAnimationRun",
        "setInnerValue",
        "onChange",
        "onBlur",
        "onKeyDown"
    ]), _rest1 = _sliced_to_array(_rest, 1), ref = _rest1[0];
    var _useState = _sliced_to_array((0, _react.useState)(value ? "".concat(String(value).length, "ch") : _utils1.defaultCharacterWidth), 2), dynamicWidth = _useState[0], setDynamicWidth = _useState[1];
    var _useState1 = _sliced_to_array((0, _react.useState)(value), 2), lastValidValue = _useState1[0], setLastValidValue = _useState1[1];
    var _useState2 = _sliced_to_array((0, _react.useState)(undefined), 2), errorClass = _useState2[0], setErrorClass = _useState2[1];
    var _useState3 = _sliced_to_array((0, _react.useState)(), 2), errorValue = _useState3[0], setErrorValue = _useState3[1];
    var inputHelperRef = (0, _react.useRef)(null);
    var wrapperRef = (0, _react.useRef)(null);
    var textWrapperRef = (0, _react.useRef)(null);
    var inputRef = (0, _react.useRef)(null);
    var inputForkRef = (0, _hooks.useForkRef)(inputRef, ref);
    var solidViewClass = segmentation === 'solid' ? _NumberInputtokens.classes.solidView : undefined;
    var manualInputClass = isManualInput ? _NumberInputtokens.classes.manualInput : undefined;
    var getInputWidth = function getInputWidth() {
        var firstRender = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
        var _inputHelperRef_current;
        if (!firstRender && ((_inputHelperRef_current = inputHelperRef.current) === null || _inputHelperRef_current === void 0 ? void 0 : _inputHelperRef_current.clientWidth)) {
            var _inputHelperRef_current1;
            return "".concat((_inputHelperRef_current1 = inputHelperRef.current) === null || _inputHelperRef_current1 === void 0 ? void 0 : _inputHelperRef_current1.clientWidth, "px");
        }
        if (value) {
            return "".concat(String(value).length, "ch");
        }
        return _utils1.defaultCharacterWidth;
    };
    var setValues = function setValues(event, newValue) {
        setLastValidValue(newValue);
        setInnerValue(newValue);
        if (onChange) {
            onChange(event, newValue);
        }
    };
    var validateValue = function validateValue(newValue) {
        if (!newValue || !(0, _utils.isNumber)(newValue)) {
            setValues(null, '');
            setIsAnimationRun(false);
            return;
        }
        var resValue = Number(newValue);
        if (max !== undefined && resValue > max) {
            setErrorClass(_NumberInputtokens.classes.errorAnimation);
            setErrorValue(max);
            setIsAnimationRun(true);
            return;
        }
        if (min !== undefined && resValue < min) {
            setErrorClass(_NumberInputtokens.classes.errorAnimation);
            setErrorValue(min);
            setIsAnimationRun(true);
            return;
        }
        if (String(newValue).endsWith('.')) {
            setValues(null, Number(newValue));
            setIsAnimationRun(false);
            return;
        }
        if (precision !== undefined) {
            var preciseNewValue = Number((0, _utils1.getPreciseValue)(newValue, precision));
            setValues(null, preciseNewValue);
        }
        setIsAnimationRun(false);
    };
    var handleManualInputChange = function handleManualInputChange(event) {
        var _textWrapperRef_current, _wrapperRef_current;
        if (!isManualInput || disabled) {
            return;
        }
        setIsAnimationRun(true);
        var _event_target = event.target, newValue = _event_target.value;
        if (!(0, _utils.isNumber)(lastValidValue) && lastValidValue !== '' && !newValue) {
            return;
        }
        if (!newValue) {
            setInnerValue('');
            if (onChange) {
                onChange(event, '');
            }
            return;
        }
        var cleanValue = newValue.replace(_utils1.excludingNumberSchema, '');
        if (cleanValue.endsWith('.') || cleanValue === '-') {
            setInnerValue(cleanValue);
            if (onChange) {
                onChange(event, cleanValue);
            }
            return;
        }
        var isValid = _utils1.numberSchema.test(cleanValue);
        if (!isValid) {
            setValues(event, lastValidValue);
            return;
        }
        if ((textWrapperRef === null || textWrapperRef === void 0 ? void 0 : textWrapperRef.current) && (wrapperRef === null || wrapperRef === void 0 ? void 0 : wrapperRef.current) && (textWrapperRef === null || textWrapperRef === void 0 ? void 0 : (_textWrapperRef_current = textWrapperRef.current) === null || _textWrapperRef_current === void 0 ? void 0 : _textWrapperRef_current.clientWidth) > (wrapperRef === null || wrapperRef === void 0 ? void 0 : (_wrapperRef_current = wrapperRef.current) === null || _wrapperRef_current === void 0 ? void 0 : _wrapperRef_current.clientWidth)) {
            wrapperRef.current.scrollLeft = textWrapperRef.current.offsetWidth - textWrapperRef.current.offsetLeft || 0;
        }
        setValues(event, cleanValue);
    };
    var handleClickInputWrapper = function handleClickInputWrapper() {
        if (!isManualInput || !inputRef.current) {
            return;
        }
        if (!isInputFocused) {
            inputRef.current.select();
        }
        setIsInputFocused(true);
    };
    var handleBlur = function handleBlur(event) {
        validateValue(value);
        setIsInputFocused(false);
        if (onBlur) {
            onBlur(event);
        }
    };
    var handleKeyDown = function handleKeyDown(event) {
        if (!isManualInput || disabled) {
            return;
        }
        if (event.keyCode === _constants.keyCodes.Enter) {
            event.preventDefault();
            validateValue(value);
            if (onKeyDown) {
                onKeyDown(event);
            }
        }
    };
    var handleEndErrorAnimation = function handleEndErrorAnimation(correctValue) {
        setIsAnimationRun(false);
        setIsInputFocused(false);
        setErrorClass(undefined);
        setValues(null, correctValue);
    };
    (0, _react.useEffect)(function() {
        setDynamicWidth(getInputWidth());
    }, []);
    (0, _hooks.useDidMountEffect)(function() {
        setDynamicWidth(getInputWidth(false));
    }, [
        value
    ]);
    return /*#__PURE__*/ _react.default.createElement(_Inputstyles.InputWrapper, {
        ref: wrapperRef,
        className: (0, _utils.cx)(solidViewClass, errorClass, manualInputClass),
        isManualInput: Boolean(isManualInput),
        onClick: handleClickInputWrapper
    }, /*#__PURE__*/ _react.default.createElement(_Inputstyles.TextWrapper, {
        ref: textWrapperRef
    }, !isLoading && textBefore && /*#__PURE__*/ _react.default.createElement(_Inputstyles.AdditionalText, {
        className: _NumberInputtokens.classes.textBefore
    }, textBefore), isLoading ? /*#__PURE__*/ _react.default.createElement(_Inputstyles.Loader, null, loader || /*#__PURE__*/ _react.default.createElement(_Inputstyles.StyledSpinner, null)) : /*#__PURE__*/ _react.default.createElement(_Inputstyles.DynamicInput, null, /*#__PURE__*/ _react.default.createElement(_Inputstyles.Input, _object_spread({
        ref: inputForkRef,
        dynamicWidth: dynamicWidth,
        value: value,
        isManualInput: Boolean(isManualInput),
        tabIndex: disabled || !isManualInput ? -1 : 0,
        onChange: handleManualInputChange,
        onBlur: handleBlur,
        onKeyDown: handleKeyDown,
        onAnimationEnd: function onAnimationEnd() {
            return handleEndErrorAnimation(Number(errorValue));
        }
    }, rest)), /*#__PURE__*/ _react.default.createElement(_Inputstyles.InputWidthHelper, {
        ref: inputHelperRef
    }, value)), !isLoading && textAfter && /*#__PURE__*/ _react.default.createElement(_Inputstyles.AdditionalText, {
        className: _NumberInputtokens.classes.textAfter
    }, textAfter)));
});
