import _extends from "@babel/runtime/helpers/esm/extends";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
var _dec, _class, _PasswordInput;
import React from 'react';
import { globalObject, isBrowser } from '@skbkontur/global-object';
import { locale } from "../../../lib/locale/decorators";
import { RenderLayer } from "../../../internal/RenderLayer";
import { isNonNullable } from "../../../lib/utils";
import { isKeyCapsLock } from "../../../lib/events/keyboard/identifiers";
import { KeyboardEventCodes as Codes } from "../../../lib/events/keyboard/KeyboardEventCodes";
import { Input } from "../../Input";
import { isIE11 } from "../../../lib/client";
import { CommonWrapper } from "../../../internal/CommonWrapper";
import { ThemeContext } from "../../../lib/theming/ThemeContext";
import { cx } from "../../../lib/theming/Emotion";
import { rootNode } from "../../../lib/rootNode";
import { withSize } from "../../../lib/size/SizeDecorator";
import { createPropsGetter } from "../../../lib/createPropsGetter";
import { styles } from "../PasswordInput.styles";
import { PasswordInputIcon } from "../PasswordInputIcon";
import { PasswordInputLocaleHelper } from "../locale";
export var PasswordInputDataTids = {
  root: 'PasswordInput',
  capsLockDetector: 'PasswordInputCapsLockDetector',
  eyeIcon: 'PasswordInputEyeIcon'
};

/**
 * Однострочное поле для ввода пароля, в котором символы заменяются на точки.
 */

export var PasswordInput = (_dec = locale('PasswordInput', PasswordInputLocaleHelper), rootNode(_class = _dec(_class = withSize(_class = (_PasswordInput = /*#__PURE__*/function (_React$PureComponent) {
  function PasswordInput() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _React$PureComponent.call.apply(_React$PureComponent, [this].concat(args)) || this;
    _this.state = {
      visible: false,
      focused: false,
      capsLockEnabled: false
    };
    _this.getProps = createPropsGetter({});

    /** Программно устанавливает фокус на поле.
     * Появляется фокусная рамка, элемент получает клавиатурные события и воспринимается как текущий элемент для чтения скринридерами.
     * @public
     */
    _this.focus = function () {
      if (_this.input) {
        _this.input.focus();
      }
    };

    /** Программно снимает фокус с кнопки.
     * @public
     */
    _this.blur = function () {
      if (_this.input) {
        _this.input.blur();
      }
    };
    _this.handleKeyPress = function (e) {
      var _this$props = _this.props,
        onKeyPress = _this$props.onKeyPress,
        detectCapsLock = _this$props.detectCapsLock;
      if (onKeyPress) {
        onKeyPress(e);
      }
      if (!detectCapsLock) {
        return;
      }
      var capsLockEnabled = e.getModifierState(Codes.CapsLock);
      _this.setState({
        capsLockEnabled: capsLockEnabled
      });
    };
    _this.handleKeydown = function (e) {
      var _this2 = _this,
        _this2$props = _this2.props,
        detectCapsLock = _this2$props.detectCapsLock,
        onKeyDown = _this2$props.onKeyDown,
        capsLockEnabled = _this2.state.capsLockEnabled;
      if (onKeyDown) {
        onKeyDown(e);
      }
      if (!detectCapsLock) {
        return;
      }
      if (isKeyCapsLock(e) && isNonNullable(capsLockEnabled)) {
        _this.setState({
          capsLockEnabled: !capsLockEnabled
        });
      }
    };
    _this.handleToggleVisibility = function () {
      _this.setState(function (prevState) {
        return {
          visible: !prevState.visible
        };
      }, _this.focusOnInput);
    };
    _this.focusOnInput = function () {
      if (_this.input) {
        _this.input.focus();
      }
    };
    _this.handleFocus = function (event) {
      if (_this.state.focused) {
        return;
      }
      _this.setState({
        focused: true
      });
      if (_this.props.onFocus) {
        _this.props.onFocus(event);
      }
    };
    _this.handleFocusOutside = function () {
      _this.hideSymbols();
      if (_this.state.focused) {
        _this.setState({
          focused: false
        });
      }
    };
    _this.renderEye = function () {
      var capsLockEnabled = _this.state.capsLockEnabled;
      return /*#__PURE__*/(
        React.createElement("span", {
          className: styles.iconWrapper()
        }, capsLockEnabled && /*#__PURE__*/
        React.createElement("span", {
          className: styles.capsLockDetector(),
          "data-tid": PasswordInputDataTids.capsLockDetector
        }), /*#__PURE__*/

        React.createElement("span", {
          className: cx(styles.toggleVisibility(_this.theme), _this.getEyeWrapperClassname())
        }, !_this.props.disabled && /*#__PURE__*/
        React.createElement("button", {
          type: "button",
          "aria-label": _this.state.visible ? _this.locale.eyeClosedAriaLabel : _this.locale.eyeOpenedAriaLabel,
          onClick: _this.handleToggleVisibility,
          className: styles.icon(),
          "data-tid": PasswordInputDataTids.eyeIcon
        }, /*#__PURE__*/

        React.createElement(PasswordInputIcon, {
          size: _this.size,
          visible: _this.state.visible
        }))))
      );
    };
    _this.refInput = function (element) {
      _this.input = element;
    };
    _this.hideSymbols = function () {
      _this.setState({
        visible: false
      });
    };
    _this.renderMain = function (props) {
      return /*#__PURE__*/(
        React.createElement(RenderLayer, {
          active: _this.state.focused,
          onFocusOutside: _this.handleFocusOutside,
          onClickOutside: _this.handleFocusOutside
        }, /*#__PURE__*/

        React.createElement("div", {
          "data-tid": PasswordInputDataTids.root,
          className: styles.root()
        }, /*#__PURE__*/
        React.createElement(Input, _extends({
          ref: _this.refInput,
          type: _this.state.visible ? 'text' : 'password',
          onKeyDown: _this.handleKeydown,
          onKeyPress: _this.handleKeyPress,
          rightIcon: _this.renderEye(),
          onFocus: _this.handleFocus
        }, props))))
      );
    };
    return _this;
  }
  _inheritsLoose(PasswordInput, _React$PureComponent);
  var _proto = PasswordInput.prototype;
  _proto.componentDidMount = function componentDidMount() {
    if (this.props.detectCapsLock) {
      this.setState({
        capsLockEnabled: null
      });
    } // @ts-expect-error: IE-specific API.
    if (isIE11 && isBrowser(globalObject) && !globalObject.document.msCapsLockWarningOff) {
      // @ts-expect-error: Read the comment above.
      // turns off default ie capslock warning
      globalObject.document.msCapsLockWarningOff = true;
    }
  };
  PasswordInput.getDerivedStateFromProps = function getDerivedStateFromProps(props, state) {
    if (props.disabled) {
      return {
        visible: false
      };
    }
    return state;
  };
  _proto.render = function render() {
    var _this3 = this;
    return /*#__PURE__*/React.createElement(ThemeContext.Consumer, null, function (theme) {
      _this3.theme = theme;
      return /*#__PURE__*/React.createElement(CommonWrapper, _extends({
        rootNodeRef: _this3.setRootNode
      }, _this3.getProps()), _this3.renderMain);
    });
  };
  _proto.getEyeWrapperClassname = function getEyeWrapperClassname() {
    switch (this.size) {
      case 'large':
        return styles.eyeWrapperLarge(this.theme);
      case 'medium':
        return styles.eyeWrapperMedium(this.theme);
      case 'small':
      default:
        return styles.eyeWrapperSmall(this.theme);
    }
  };
  return PasswordInput;
}(React.PureComponent), _PasswordInput.__KONTUR_REACT_UI__ = 'PasswordInput', _PasswordInput.displayName = 'PasswordInput', _PasswordInput)) || _class) || _class) || _class);