"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof = require("@babel/runtime/helpers/typeof");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _react = _interopRequireWildcard(require("react"));

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

var _2 = require("../../");

var _theme = _interopRequireDefault(require("./theme.css"));

var _classnames = _interopRequireDefault(require("classnames"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(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 = {}; 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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

var transformToPaddedNumber = function transformToPaddedNumber(number) {
  return number < 10 ? "0".concat(number) : number.toString();
};

var MINUTES_STEP = 15;
/** @type {React.ComponentType<any>} */

var DurationInput = /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
  var _hours, _minutes;

  var id = _ref.id,
      value = _ref.value,
      onChange = _ref.onChange,
      onBlur = _ref.onBlur,
      onFocus = _ref.onFocus,
      onKeyDown = _ref.onKeyDown,
      autoFocus = _ref.autoFocus,
      textAlignRight = _ref.textAlignRight,
      className = _ref.className,
      error = _ref.error,
      max = _ref.max,
      size = _ref.size;
  var containerRef = (0, _react.useRef)();
  (0, _react.useImperativeHandle)(ref, function () {
    return containerRef.current;
  });

  var handleHoursChanged = function handleHoursChanged(_, hours) {
    if (!onChange) {
      return;
    }

    if (hours === '') {
      if (typeof (value === null || value === void 0 ? void 0 : value.minutes) === 'undefined') {
        onChange();
        return;
      }

      onChange({
        minutes: value === null || value === void 0 ? void 0 : value.minutes
      });
      return;
    }

    var parsedHours = parseInt(hours);

    if (!Number.isInteger(parsedHours)) {
      return;
    }

    onChange(_objectSpread(_objectSpread({}, value), {}, {
      hours: parsedHours
    }));
  };

  var handleMinutesChange = function handleMinutesChange(_, minutes) {
    if (!onChange) {
      return;
    }

    if (minutes === '') {
      if (typeof (value === null || value === void 0 ? void 0 : value.hours) === 'undefined') {
        onChange();
        return;
      }

      onChange({
        hours: value === null || value === void 0 ? void 0 : value.hours
      });
      return;
    }

    var parsedMinutes = parseInt(minutes);

    if (!Number.isInteger(parsedMinutes)) {
      return;
    }

    if (parsedMinutes > 60) {
      return;
    }

    if (parsedMinutes === 60) {
      onChange({
        hours: ((value === null || value === void 0 ? void 0 : value.hours) || 0) + 1,
        minutes: 0
      });
      return;
    }

    if (parsedMinutes < 0) {
      onChange({
        hours: ((value === null || value === void 0 ? void 0 : value.hours) || 1) - 1,
        minutes: 60 - MINUTES_STEP
      });
      return;
    }

    onChange(_objectSpread(_objectSpread({}, value), {}, {
      minutes: parsedMinutes
    }));
  };
  /**
   * This blur handler is a special one, because this input consists of multiple focus points:
   * the two inputs themselves, and the four increment/decrement buttons
   * we filter out the blur events caused by changing focus between these, so the onBlur event only
   * gets triggered when really blurring outside of the entire component
   */


  var handleBlur = function handleBlur(event) {
    var _containerRef$current, _containerRef$current2;

    if (!event.relatedTarget) {
      onBlur && onBlur(event);
      return;
    }

    var inputs = ((_containerRef$current = containerRef.current) === null || _containerRef$current === void 0 ? void 0 : _containerRef$current.getElementsByTagName('input')) || [];

    if (Array.from(inputs).find(function (node) {
      return node === event.relatedTarget;
    })) {
      return;
    }

    var buttons = ((_containerRef$current2 = containerRef.current) === null || _containerRef$current2 === void 0 ? void 0 : _containerRef$current2.getElementsByTagName('button')) || [];

    if (Array.from(buttons).find(function (node) {
      return node === event.relatedTarget;
    })) {
      return;
    }

    onBlur && onBlur(event);
  };

  var minutes = value === null || value === void 0 ? void 0 : value.minutes;

  if (Number.isInteger(minutes)) {
    minutes = transformToPaddedNumber(minutes);
  } // if it starts with 0, allow one more so we don't block typing (because we autopad the minutes)


  var maxMinuteLength = minutes && minutes.length >= 2 && minutes[0] !== '0' ? 2 : 3;
  var hours = value === null || value === void 0 ? void 0 : value.hours;

  if (Number.isInteger(hours)) {
    hours = transformToPaddedNumber(hours);
  }

  var maxHours;
  var maxMinutes;

  if (max) {
    maxHours = Math.floor(max / 60);
    maxMinutes = max % 60;
  }

  var maxHourLength;

  if (hours && maxHours) {
    maxHourLength = maxHours.toString().length; // if it starts with 0, allow one more so we don't block typing (because we autopad the hours)

    if (hours && hours.length >= maxHourLength && hours[0] === '0') {
      maxHourLength += 1;
    }
  } // Minutes are relative to the already filled in hours, so the max needs to be set on the fly


  var isMaximumMinutesLimited = max && (value === null || value === void 0 ? void 0 : value.hours) && value.hours >= maxHours || maxHours === 0;
  return /*#__PURE__*/_react.default.createElement(_2.Box, {
    id: id,
    display: "flex",
    alignItems: "center",
    ref: containerRef,
    className: (0, _classnames.default)(className, _theme.default['duration-input-numeric-container'], (0, _defineProperty2.default)({}, _theme.default['has-error'], error))
  }, /*#__PURE__*/_react.default.createElement(_2.NumericInput, (0, _extends2.default)({
    placeholder: "00",
    min: 0
  }, max ? {
    max: maxHours
  } : {}, {
    maxLength: maxHourLength,
    value: (_hours = hours) !== null && _hours !== void 0 ? _hours : '',
    onChange: handleHoursChanged,
    onBlur: handleBlur,
    onFocus: onFocus,
    onKeyDown: onKeyDown,
    type: "text",
    inputMode: "numeric",
    className: _theme.default['duration-input-numeric-input'],
    autoFocus: autoFocus,
    textAlignRight: textAlignRight,
    size: size
  })), /*#__PURE__*/_react.default.createElement(_2.NumericInput, (0, _extends2.default)({
    placeholder: "00",
    step: MINUTES_STEP
  }, !(value !== null && value !== void 0 && value.hours) ? {
    min: 0
  } : {}, isMaximumMinutesLimited ? {
    max: maxMinutes
  } : {}, {
    maxLength: maxMinuteLength,
    value: (_minutes = minutes) !== null && _minutes !== void 0 ? _minutes : '',
    onChange: handleMinutesChange,
    onBlur: handleBlur,
    onFocus: onFocus,
    onKeyDown: onKeyDown,
    type: "text",
    inputMode: "numeric",
    className: _theme.default['duration-input-numeric-input'],
    textAlignRight: textAlignRight,
    size: size
  })));
});
DurationInput.defaultProps = {
  textAlignRight: false,
  size: 'medium'
};
DurationInput.displayName = 'DurationInput';
var _default = DurationInput;
exports.default = _default;