"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
exports.__esModule = true;
exports["default"] = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _react = _interopRequireWildcard(require("react"));
var _AddressInput = _interopRequireDefault(require("../AddressInput"));
var _AddressInputItem = require("../AddressInputItem");
var _usePlacesAutocomplete = _interopRequireDefault(require("../providers/usePlacesAutocomplete"));
var _useAtlasClient = _interopRequireDefault(require("../providers/useAtlasClient"));
var _constants = require("./constants");
var _excluded = ["baseUrl", "token", "language", "locale", "debounceMs", "debounceFn", "onChange", "onClear", "onSelect", "onError", "selectOnSubmit", "optionLayout", "optionPrefix", "optionSuffix", "status"];
var _jsxFileName = "/home/builduser/work/57e038ea7326c1ec/packages/wix-design-system/dist/cjs/AtlasAddressInput/AtlasAddressInput.jsx",
  _this = void 0;
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
var AtlasAddressInput = /*#__PURE__*/_react["default"].forwardRef(function (_ref, ref) {
  var baseUrl = _ref.baseUrl,
    token = _ref.token,
    _ref$language = _ref.language,
    language = _ref$language === void 0 ? 'en' : _ref$language,
    _ref$locale = _ref.locale,
    locale = _ref$locale === void 0 ? 'en-us' : _ref$locale,
    debounceMs = _ref.debounceMs,
    debounceFn = _ref.debounceFn,
    onChange = _ref.onChange,
    onClear = _ref.onClear,
    onSelect = _ref.onSelect,
    onError = _ref.onError,
    selectOnSubmit = _ref.selectOnSubmit,
    optionLayout = _ref.optionLayout,
    optionPrefix = _ref.optionPrefix,
    optionSuffix = _ref.optionSuffix,
    statusProp = _ref.status,
    props = (0, _objectWithoutProperties2["default"])(_ref, _excluded);
  var client = (0, _useAtlasClient["default"])({
    baseUrl: baseUrl,
    token: token,
    language: language,
    locale: locale
  });
  var _usePlacesAutocomplet = (0, _usePlacesAutocomplete["default"])({
      client: client,
      debounceMs: debounceMs,
      debounceFn: debounceFn,
      onError: onError
    }),
    predictions = _usePlacesAutocomplet.predictions,
    updatePredictions = _usePlacesAutocomplet.updatePredictions,
    clearPredictions = _usePlacesAutocomplet.clearPredictions,
    loading = _usePlacesAutocomplet.loading;

  // If not loading, show the status passed from props
  var status = loading ? 'loading' : statusProp;
  var options = (0, _react.useMemo)(function () {
    return predictions.map(function (prediction) {
      return (0, _AddressInputItem.addressInputItemBuilder)({
        id: prediction.searchId,
        mainLabel: prediction.textStructure.mainText,
        secondaryLabel: prediction.textStructure.secondaryText,
        displayLabel: prediction.description,
        optionLayout: optionLayout,
        prefix: optionPrefix,
        suffix: optionSuffix,
        dataHook: _constants.dataHooks.item
      });
    });
  }, [predictions, optionLayout, optionPrefix, optionSuffix]);
  var innerRef = (0, _react.useRef)(null);
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      focus: function focus() {
        return innerRef.current && innerRef.current.focus();
      }
    };
  });
  var _onChange = (0, _react.useCallback)(function (event) {
    updatePredictions(event.target.value);
    onChange && onChange(event);
  }, [updatePredictions, onChange]);
  var _onClear = (0, _react.useCallback)(function () {
    clearPredictions();
    onClear && onClear();
  }, [clearPredictions, onClear]);
  var _onSelect = (0, _react.useCallback)(function (option) {
    var getAddress = function getAddress() {
      return client.getAddress(option.id);
    };
    onSelect && onSelect(option, getAddress);
  }, [client, onSelect]);

  // A callback which is called when the user performs a Submit-Action
  var _onManualSubmit = (0, _react.useCallback)(function (inputValue) {
    if (selectOnSubmit && onSelect && inputValue) {
      var option = (0, _AddressInputItem.addressInputItemBuilder)({
        id: inputValue,
        mainLabel: inputValue,
        displayLabel: inputValue
      });
      var getAddress = /*#__PURE__*/function () {
        var _ref2 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee() {
          var addresses;
          return _regenerator["default"].wrap(function _callee$(_context) {
            while (1) switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return client.searchAddresses(inputValue);
              case 2:
                addresses = _context.sent;
                return _context.abrupt("return", addresses[0]);
              case 4:
              case "end":
                return _context.stop();
            }
          }, _callee);
        }));
        return function getAddress() {
          return _ref2.apply(this, arguments);
        };
      }();
      onSelect(option, getAddress);
    }
  }, [selectOnSubmit, onSelect, client]);
  return /*#__PURE__*/_react["default"].createElement(_AddressInput["default"], (0, _extends2["default"])({}, props, {
    options: options,
    onChange: _onChange,
    onClear: _onClear,
    onSelect: _onSelect,
    onManuallyInput: _onManualSubmit,
    status: status,
    ref: innerRef,
    __self: _this,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 109,
      columnNumber: 7
    }
  }));
});
AtlasAddressInput.displayName = 'AtlasAddressInput';
var _default = exports["default"] = AtlasAddressInput;