"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.KeypadDecorator = exports.KeypadBase = exports.Keypad = exports["default"] = void 0;

var _jsxRuntime = require("react/jsx-runtime");

var _handle = require("@enact/core/handle");

var _hoc = _interopRequireDefault(require("@enact/core/hoc"));

var _kind = _interopRequireDefault(require("@enact/core/kind"));

var _Layout = _interopRequireWildcard(require("@enact/ui/Layout"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _compose = _interopRequireDefault(require("ramda/src/compose"));

var _react = require("react");

var _$L = _interopRequireDefault(require("../internal/$L"));

var _Button = _interopRequireDefault(require("../Button"));

var _Skinnable = _interopRequireDefault(require("../Skinnable"));

var _KeypadModule = _interopRequireDefault(require("./Keypad.module.css"));

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

var KEY_LIST = [{
  text: '1'
}, {
  text: '2',
  label: 'abc'
}, {
  text: '3',
  label: 'def'
}, {
  text: '4',
  label: 'ghi'
}, {
  text: '5',
  label: 'jkl'
}, {
  text: '6',
  label: 'mno'
}, {
  text: '7',
  label: 'pqrs'
}, {
  text: '8',
  label: 'tuv'
}, {
  text: '9',
  label: 'wxyz'
}, {
  text: '*'
}, {
  text: '0'
}, {
  text: '#'
}, {
  icon: 'phone'
}, {
  icon: 'arrowuturn'
}];
/**
 * Renders an Agate-styled Key button.
 *
 * @class Key
 * @memberof agate/Keypad
 * @ui
 * @public
 */

var Key = (0, _kind["default"])({
  name: 'Key',
  propTypes:
  /** @lends agate/Keypad.Key.prototype */
  {
    /**
     * The icon displayed on the key.
     *
     * @type {String}
     * @public
     */
    icon: _propTypes["default"].string,

    /**
     * Text displayed below the number/icon/symbol on the key.
     *
     * @type {String}
     * @public
     */
    label: _propTypes["default"].string,

    /**
     * Called when this button is clicked. Includes the 'key' key in its event payload to let the clicker know what was clicked inside their callback.
     *
     * @type {Function}
     * @param {Object} event
     * @public
     */
    onKeyButtonClick: _propTypes["default"].func,

    /**
     * Text displayed in the center of the key.
     *
     * @type {String}
     * @public
     */
    text: _propTypes["default"].string
  },
  styles: {
    css: _KeypadModule["default"],
    className: 'key'
  },
  handlers: {
    onClick: (0, _handle.handle)((0, _handle.forward)('onClick'), (0, _handle.adaptEvent)(function (ev, _ref) {
      var key = _ref.children;
      return {
        key: key
      };
    }, (0, _handle.forward)('onKeyButtonClick')))
  },
  render: function render(_ref2) {
    var children = _ref2.children,
        label = _ref2.label,
        text = _ref2.text,
        rest = _objectWithoutProperties(_ref2, ["children", "label", "text"]);

    delete rest.onKeyButtonClick;
    return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: _KeypadModule["default"].keyContainer,
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_Button["default"], _objectSpread(_objectSpread({}, rest), {}, {
        css: _KeypadModule["default"],
        icon: children,
        minWidth: false,
        role: null,
        size: "large",
        children: [text || text === 0 ? /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: _KeypadModule["default"].text,
          children: text
        }) : null, label || label === 0 ? /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: _KeypadModule["default"].label,
          children: label
        }) : null]
      }))
    });
  }
});
/**
 * The basic Layout of a Keypad component.
 *
 * @class KeypadBase
 * @memberof agate/Keypad
 * @extends agate/Keypad.Key
 * @ui
 * @public
 */

var KeypadBase = (0, _kind["default"])({
  name: 'Keypad',
  propTypes:
  /** @lends agate/Keypad.KeypadBase.prototype */
  {
    /**
     * Applies a disabled style and the control becomes non-interactive.
     *
     * @type {Boolean}
     * @default false
     * @public
     */
    disabled: _propTypes["default"].bool,

    /**
     * Called when a button is clicked. Includes the 'key' key in its event payload, updates the state and the input value accordingly.
     *
     * @type {Function}
     * @param {Object} event
     * @public
     */
    onKeyButtonClick: _propTypes["default"].func
  },
  styles: {
    css: _KeypadModule["default"],
    className: 'keypad'
  },
  render: function render(_ref3) {
    var disabled = _ref3.disabled,
        _onKeyButtonClick = _ref3.onKeyButtonClick,
        rest = _objectWithoutProperties(_ref3, ["disabled", "onKeyButtonClick"]);

    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Layout["default"], _objectSpread(_objectSpread({}, rest), {}, {
      align: "center end",
      className: _KeypadModule["default"].keypad,
      inline: true,
      wrap: true,
      children: KEY_LIST.map(function (keyText, rowIndex) {
        var icon = keyText.icon,
            text = keyText.text;
        var isIcon = icon === 'arrowuturn' || icon === 'phone';
        var ariaLabel = text;

        if (icon === 'arrowuturn') {
          ariaLabel = (0, _$L["default"])('backspace');
        } else if (icon === 'phone') {
          ariaLabel = (0, _$L["default"])('call');
        }

        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Layout.Cell, {
          "aria-label": ariaLabel,
          component: Key,
          disabled: disabled,
          onKeyButtonClick: function onKeyButtonClick() {
            return _onKeyButtonClick(isIcon ? icon : text);
          },
          shrink: true,
          label: keyText.label,
          text: isIcon ? null : text,
          children: isIcon ? icon : null
        }, "key".concat(rowIndex, "-").concat(text));
      })
    }));
  }
});
/**
 * A Keypad component with an Input to display the outcome.
 *
 * @class KeypadBehaviorDecorator
 * @hoc
 * @memberof agate/Keypad
 * @private
 */

exports.KeypadBase = KeypadBase;
var KeypadBehaviorDecorator = (0, _hoc["default"])(function (config, Wrapped) {
  var _class, _temp;

  return _temp = _class = /*#__PURE__*/function (_Component) {
    _inherits(_class, _Component);

    var _super = _createSuper(_class);

    function _class(props) {
      var _this;

      _classCallCheck(this, _class);

      _this = _super.call(this, props);

      _this.handleInputValue = function (keyValue) {
        var _this$state = _this.state,
            charIndex = _this$state.charIndex,
            keypadInput = _this$state.keypadInput;
        var newKeypadInput = keypadInput;
        var newCharIndex;

        switch (keyValue) {
          case 'arrowuturn':
          case 'Backspace':
            newCharIndex = charIndex;
            newKeypadInput = newKeypadInput.substring(0, charIndex - 1) + newKeypadInput.substring(charIndex, newKeypadInput.length);
            newCharIndex = newCharIndex - 1;
            break;

          case 'ArrowLeft':
            if (charIndex >= 0) {
              newCharIndex = charIndex;
              newCharIndex = newCharIndex - 1;
            }

            break;

          case 'ArrowRight':
            newCharIndex = charIndex;
            newCharIndex = newCharIndex + 1;
            break;

          case 'Delete':
            newCharIndex = charIndex;
            newKeypadInput = newKeypadInput.substring(0, charIndex) + newKeypadInput.substring(charIndex + 1, newKeypadInput.length);
            newCharIndex = newCharIndex - 1;
            break;

          case 'ArrowUp':
          case 'ArrowDown':
            // do nothing;
            break;

          case 'phone':
            // method to call dialed number (keypadInput);
            newCharIndex = 0;
            newKeypadInput = '';
            break;

          default:
            newCharIndex = charIndex;
            newKeypadInput = newKeypadInput.substring(0, charIndex) + keyValue + newKeypadInput.substring(charIndex);
            newCharIndex = newCharIndex + 1;
            break;
        }

        if (keypadInput !== newKeypadInput) {
          (0, _handle.forward)('onChange', {
            value: newKeypadInput
          }, _this.props);
        }

        _this.setState({
          charIndex: newCharIndex,
          keypadInput: newKeypadInput
        });
      };

      _this.state = {
        charIndex: 0,
        keypadInput: ''
      };
      return _this;
    }

    _createClass(_class, [{
      key: "render",
      value: function render() {
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread(_objectSpread({}, this.props), {}, {
          onKeyButtonClick: this.handleInputValue
        }));
      }
    }]);

    return _class;
  }(_react.Component), _class.displayName = 'KeypadBehaviorDecorator', _class.propTypes =
  /** @lends agate/Keypad.KeypadBehaviorDecorator.prototype */
  {
    /**
     * Applies a disabled style and the control becomes non-interactive.
     *
     * @type {Boolean}
     * @default false
     * @public
     */
    disabled: _propTypes["default"].bool,

    /**
     * Called when a button is clicked. Includes the 'key' key in its event payload, updates the state and the input value accordingly.
     *
     * @type {Function}
     * @param {Object} event
     * @public
     */
    handleInputValue: _propTypes["default"].func,

    /**
     * Called when the input value is changed.
     *
     * @type {Function}
     * @param {Object} event
     * @public
     */
    onChange: _propTypes["default"].func,

    /**
     * The value of the input.
     *
     * @type {String}
     * @public
     */
    value: _propTypes["default"].string
  }, _temp;
});
/**
 * Applies Agate specific behaviors to [KeypadBase]{@link agate/Keypad.KeypadBase}
 *
 * @hoc
 * @memberof agate/Keypad
 * @mixes agate/Skinnable.Skinnable
 * @public
 */

var KeypadDecorator = (0, _compose["default"])(KeypadBehaviorDecorator, _Skinnable["default"]);
/**
 * Provides Agate-themed keypad components and behaviors. Used to display a sequence of numbers and buttons, like a keyboard.
 *
 * @class Keypad
 * @memberof agate/Keypad
 * @extends agate/Keypad.KeypadBase
 * @mixes agate/Keypad.KeypadDecorator
 * @public
 * @ui
 */

exports.KeypadDecorator = KeypadDecorator;
var Keypad = KeypadDecorator(KeypadBase);
exports.Keypad = Keypad;
var _default = Keypad;
exports["default"] = _default;