"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = exports.BASE_ATLAS_URL = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _react = require("react");
var _http = require("@wix/ambassador-wix-atlas-service-web/http");
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var BASE_ATLAS_URL = exports.BASE_ATLAS_URL = '/wix-atlas-service-web';

// Client for fetching autocomplete predictions from Atlas
var useAtlasClient = function useAtlasClient() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
    _ref$baseUrl = _ref.baseUrl,
    baseUrl = _ref$baseUrl === void 0 ? BASE_ATLAS_URL : _ref$baseUrl,
    token = _ref.token,
    language = _ref.language,
    locale = _ref.locale;
  // languageHeader to set language for Atlas Service 'x-wix-linguist': language|locale|isPrimaryLanguage|token
  var languageHeader = "".concat(language, "|").concat(locale, "|false|").concat(token);
  var atlas = (0, _react.useMemo)(function () {
    return (0, _http.WixAtlasServiceWeb)(baseUrl);
  }, [baseUrl]);
  // Atlas Ambassador autocomplete service (memoized)
  var autocompleteService = (0, _react.useMemo)(function () {
    return atlas.AutocompleteServiceV2()({
      Authorization: token,
      'x-wix-linguist': languageHeader
    });
  }, [atlas, token, languageHeader]);
  // Atlas Ambassador places service (memoized)
  var placesService = (0, _react.useMemo)(function () {
    return atlas.PlacesServiceV2()({
      Authorization: token,
      'x-wix-linguist': languageHeader
    });
  }, [atlas, token, languageHeader]);
  // Atlas Ambassador location service (memoized)
  var locationService = (0, _react.useMemo)(function () {
    return atlas.LocationServiceV2()({
      Authorization: token,
      'x-wix-linguist': languageHeader
    });
  }, [atlas, token, languageHeader]);
  var fetchPredictions = (0, _react.useCallback)(/*#__PURE__*/function () {
    var _ref2 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee(value, requestOptions) {
      var _yield$autocompleteSe, predictions;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return autocompleteService.predict(_objectSpread(_objectSpread({}, requestOptions), {}, {
              input: value
            }));
          case 2:
            _yield$autocompleteSe = _context.sent;
            predictions = _yield$autocompleteSe.predictions;
            return _context.abrupt("return", predictions);
          case 5:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x, _x2) {
      return _ref2.apply(this, arguments);
    };
  }(), [autocompleteService]);
  var getAddress = (0, _react.useCallback)(/*#__PURE__*/function () {
    var _ref3 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee2(searchId) {
      var _yield$placesService$, address;
      return _regenerator["default"].wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return placesService.getPlace({
              searchId: searchId
            });
          case 2:
            _yield$placesService$ = _context2.sent;
            address = _yield$placesService$.place.address;
            return _context2.abrupt("return", address);
          case 5:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }));
    return function (_x3) {
      return _ref3.apply(this, arguments);
    };
  }(), [placesService]);
  var searchAddresses = (0, _react.useCallback)(/*#__PURE__*/function () {
    var _ref4 = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee3(query) {
      var _yield$locationServic, searchResults, addresses;
      return _regenerator["default"].wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            _context3.next = 2;
            return locationService.search({
              query: query
            });
          case 2:
            _yield$locationServic = _context3.sent;
            searchResults = _yield$locationServic.searchResults;
            addresses = searchResults.map(function (_ref5) {
              var address = _ref5.address;
              return address;
            });
            return _context3.abrupt("return", addresses);
          case 6:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }));
    return function (_x4) {
      return _ref4.apply(this, arguments);
    };
  }(), [locationService]);
  return {
    /** callback that fetches predictions from Atlas
    * @param {string} value Input text we want predictions for.
    * @param {AtlasRequestOptions} requestOptions (optional) Options to customize predictions: {
      *  @property { filterType: "zip_code" | "country_code", filterValue: string } filterBy
              (optional) filter results by country or zip code;
      *  @property {latitude: number, longitude: number} location
              (optional) the point around which you wish to retrieve place information;
      *  @property {latitude: number, longitude: number} origin
              (optional) the origin point from which to calculate straight-line distance to the destination;
      *  @property {number} radius (optional) the distance (in meters) within which to return place results;
    * }
    * @returns {Promise<Prediction[]>} */
    fetchPredictions: fetchPredictions,
    /** callback that fetches details for a place given its atlas `searchId`
     * @param {string} searchId identifier for atlas prediction result we want to get additional details for
     * @returns {Promise<Address>} */
    getAddress: getAddress,
    /** callback that searches for addresses matching given value
     * @param {string} query Input text to search address for
     * @returns {Promise<Address[]>}
     */
    searchAddresses: searchAddresses,
    /** whether component is ready */
    ready: true
  };
};
var _default = exports["default"] = useAtlasClient;