"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ModalMapView = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _helpers = require("./helpers");
var _ModalMapView = require("./ModalMapView.l10n");
var style = _interopRequireWildcard(require("./ModalMapView.module.css"));
var _helpers2 = require("../../../../helpers");
var _shared__ = require("../../../__shared__");
var _helpers3 = require("../../../helpers");
var _helpers4 = require("../../helpers");
const _excluded = ["items", "nights", "visible", "onClose"];
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (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 (const 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); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
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) { _defineProperty(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; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
let memoizedSelected;
const ModalMapView = _ref => {
  var _selected$features;
  let _ref$items = _ref.items,
    items = _ref$items === void 0 ? [] : _ref$items,
    _ref$nights = _ref.nights,
    nights = _ref$nights === void 0 ? 1 : _ref$nights,
    visible = _ref.visible,
    onClose = _ref.onClose,
    others = _objectWithoutProperties(_ref, _excluded);
  const _useLocale = (0, _locale.useLocale)(),
    translate = _useLocale.translate;
  const _useStore = (0, _dataSources.useStore)(),
    _useStore$value = _useStore.value,
    currency = _useStore$value.currency,
    _useStore$value$finde = _useStore$value.finder,
    finder = _useStore$value$finde === void 0 ? {} : _useStore$value$finde,
    _useStore$value$forwa = _useStore$value.forwarder,
    forwarder = _useStore$value$forwa === void 0 ? {} : _useStore$value$forwa,
    hotel = _useStore$value.hotel,
    locale = _useStore$value.locale,
    _useStore$value$tags = _useStore$value.tags,
    _useStore$value$tags2 = _useStore$value$tags === void 0 ? {} : _useStore$value$tags,
    _useStore$value$tags3 = _useStore$value$tags2.options,
    places = _useStore$value$tags3 === void 0 ? [] : _useStore$value$tags3;
  const mapRef = (0, _react.useRef)();
  const _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    busy = _useState2[0],
    setBusy = _useState2[1];
  const _useState3 = (0, _react.useState)(),
    _useState4 = _slicedToArray(_useState3, 2),
    map = _useState4[0],
    setMap = _useState4[1];
  const _useState5 = (0, _react.useState)(false),
    _useState6 = _slicedToArray(_useState5, 2),
    ready = _useState6[0],
    setReady = _useState6[1];
  const _useState7 = (0, _react.useState)(),
    _useState8 = _slicedToArray(_useState7, 2),
    selected = _useState8[0],
    setSelected = _useState8[1];
  const theme = _ui.Theme.get();
  const _customMarker = (0, _helpers.customMarker)(theme),
    icon = _customMarker.icon,
    label = _customMarker.label;
  const accent = theme.accent,
    base = theme.base;
  const _ref2 = finder || {},
    _ref2$place = _ref2.place,
    _ref2$place2 = _ref2$place === void 0 ? {} : _ref2$place,
    title = _ref2$place2.title;
  const currencyFormatProps = {
    currency,
    fancy: true,
    locale,
    maximumFractionDigits: 0,
    minimumFractionDigits: 0,
    symbol: true
  };
  (0, _react.useEffect)(() => {
    if (!ready) return;
    (0, _helpers.loadGMaps)().then(() => {
      const bounds = new window.google.maps.LatLngBounds();
      const map = new window.google.maps.Map(mapRef.current, {
        fullscreenControl: false,
        mapTypeControl: false,
        styles: [{
          featureType: 'poi.business',
          elementType: 'labels',
          stylers: [{
            visibility: 'off'
          }]
        }]
      });
      map.addListener('click', () => setSelected());
      map.addListener('dragstart', () => setSelected());
      setMap(map);
      setReady();
      if (!visible) return;
      setSelected(undefined);
      map.markers = map.markers || [];
      map.markers.forEach(marker => marker.setMap());
      map.markers = [];
      items.forEach(function () {
        let dataSource = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        const item = _objectSpread(_objectSpread({}, dataSource), {}, {
          position: {
            lat: dataSource.latitude,
            lng: dataSource.longitude
          }
        });
        const price = item.price,
          position = item.position;
        const text = (0, _locale.currencyFormat)(_objectSpread(_objectSpread({}, currencyFormatProps), {}, {
          value: price
        }));
        const marker = new window.google.maps.Marker({
          map,
          position,
          icon,
          label: _objectSpread(_objectSpread({}, label), {}, {
            text
          })
        });
        marker.addListener('click', () => setSelected(item));
        marker.addListener('mouseover', () => highlightMarker(marker, item));
        marker.addListener('mouseout', () => memoizedSelected !== item ? resetMarker(marker, item) : undefined);
        map.markers.push(marker);
        bounds.extend(position);
      });
      if (items.length > 0) map.fitBounds(bounds);
    }).catch(() => {
      _dataSources.Event.publish(_helpers3.EVENT.NOTIFICATION, _objectSpread({
        error: true
      }, _ModalMapView.L10N.NOTIFICATION_ERROR_MAP));
      onClose();
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ready]);
  (0, _react.useEffect)(() => {
    if (!visible) return;
    setReady(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [items, visible]);
  (0, _react.useEffect)(() => {
    memoizedSelected = selected;
    if (!map || !items.length) return;
    if (selected) map.panTo(selected.position);
    const itemIndex = selected ? items.findIndex(_ref3 => {
      let id = _ref3.id;
      return id === selected.id;
    }) : -1;
    map.markers.forEach((marker, index) => {
      index === itemIndex ? highlightMarker(marker, items[index]) : resetMarker(marker, items[index], index);
    });

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selected]);
  const highlightMarker = function (marker) {
    let _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      price = _ref4.price;
    marker.setIcon(_objectSpread(_objectSpread({}, icon), {}, {
      fillColor: accent,
      strokeColor: accent,
      scale: 1.1
    }));
    marker.setLabel(_objectSpread(_objectSpread({}, label), {}, {
      color: base,
      text: priceMarker(price)
    }));
    marker.setZIndex(1024);
  };
  const resetMarker = function (marker) {
    let _ref5 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      price = _ref5.price;
    let index = arguments.length > 2 ? arguments[2] : undefined;
    marker.setIcon(icon);
    marker.setLabel(_objectSpread(_objectSpread({}, label), {}, {
      text: priceMarker(price)
    }));
    marker.setZIndex(index);
  };
  const priceMarker = price => (0, _locale.currencyFormat)(_objectSpread(_objectSpread({}, currencyFormatProps), {}, {
    value: price
  }));
  const handlePress = () => {
    setBusy(false);
    setTimeout(() => {
      const id = selected.id;
      const _ref6 = places.find(function () {
          let _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
            isHotel = _ref7.isHotel,
            _ref7$id = _ref7.id,
            ids = _ref7$id === void 0 ? [] : _ref7$id;
          return isHotel && ids.includes(id.toString());
        }) || {},
        value = _ref6.value;
      window.location.href = "".concat(forwarder.rates).concat((0, _helpers3.toUrlParams)(_objectSpread(_objectSpread(_objectSpread({}, (0, _helpers2.fetchUrlParams)(window.location.search)), (0, _helpers4.getFinderParams)(_objectSpread(_objectSpread(_objectSpread({}, finder), {
        place: {
          id: undefined,
          value
        }
      }), {}, {
        hotel
      }))), {}, {
        idtokenprovider: id
      })));
    }, _helpers3.SUBMIT_DELAY);
  };
  return /*#__PURE__*/_react.default.createElement(_ui.Modal, _extends({}, others, {
    title,
    visible,
    onClose,
    fit: true,
    className: [style.modal, others.className]
  }), /*#__PURE__*/_react.default.createElement(_ui.View, {
    ref: mapRef,
    className: style.map
  }), /*#__PURE__*/_react.default.createElement(_shared__.Card, {
    className: (0, _ui.styles)(style.card, selected && style.visible)
  }, /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.image,
    style: selected !== null && selected !== void 0 && selected.images ? {
      backgroundImage: "url(".concat(selected === null || selected === void 0 ? void 0 : selected.images[0], ")")
    } : undefined
  }), /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.content
  }, /*#__PURE__*/_react.default.createElement(_ui.Text, {
    bold: true,
    headline: true
  }, selected === null || selected === void 0 ? void 0 : selected.name), /*#__PURE__*/_react.default.createElement(_ui.Text, {
    action: true,
    light: true,
    className: style.location
  }, selected === null || selected === void 0 || (_selected$features = selected.features) === null || _selected$features === void 0 ? void 0 : _selected$features.location), /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.anchor
  }), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true
  }, /*#__PURE__*/_react.default.createElement(_ui.View, null, /*#__PURE__*/_react.default.createElement(_ui.Text, {
    bold: true
  }, (0, _locale.currencyFormat)(_objectSpread(_objectSpread({}, currencyFormatProps), {}, {
    fancy: false,
    symbol: false,
    value: selected === null || selected === void 0 ? void 0 : selected.price
  }))), /*#__PURE__*/_react.default.createElement(_ui.Text, {
    light: true,
    small: true
  }, (0, _locale.currencyFormat)(_objectSpread(_objectSpread({}, currencyFormatProps), {}, {
    fancy: false,
    symbol: false,
    value: (selected === null || selected === void 0 ? void 0 : selected.price) > 0 && nights > 0 && (selected === null || selected === void 0 ? void 0 : selected.price) / nights
  })), ' ', translate(_ModalMapView.L10N.LABEL_PER_NIGHT))), /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.anchor
  }), /*#__PURE__*/_react.default.createElement(_ui.Button, {
    busy: busy,
    small: true,
    onPress: handlePress
  }, translate(_ModalMapView.L10N.ACTION_VIEW_MORE))))));
};
exports.ModalMapView = ModalMapView;
ModalMapView.propTypes = {
  items: _propTypes.default.arrayOf(_propTypes.default.shape({})),
  nights: _propTypes.default.number,
  title: _propTypes.default.string,
  visible: _propTypes.default.bool,
  onClose: _propTypes.default.func
};
ModalMapView.displayName = 'Mirai:Core:Rates:ModalMapView';
//# sourceMappingURL=ModalMapView.js.map