"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 _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 {
      items = [],
      nights = 1,
      visible,
      onClose
    } = _ref,
    others = _objectWithoutProperties(_ref, _excluded);
  const {
    translate
  } = (0, _locale.useLocale)();
  const {
    value: {
      currency,
      finder = {},
      forwarder = {},
      hotel,
      locale,
      tags: {
        options: places = []
      } = {}
    }
  } = (0, _dataSources.useStore)();
  const mapRef = (0, _react.useRef)();
  const [busy, setBusy] = (0, _react.useState)(false);
  const [map, setMap] = (0, _react.useState)();
  const [ready, setReady] = (0, _react.useState)(false);
  const [selected, setSelected] = (0, _react.useState)();
  const theme = _ui.Theme.get();
  const {
    icon,
    label
  } = (0, _helpers.customMarker)(theme);
  const {
    accent,
    base
  } = theme;
  const {
    place: {
      title
    } = {}
  } = finder || {};
  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,
          position
        } = item;
        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(_ref2 => {
      let {
        id
      } = _ref2;
      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 {
      price
    } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    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 {
      price
    } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    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;
      const {
        value
      } = places.find(function () {
        let {
          isHotel,
          id: ids = []
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        return isHotel && ids.includes(id.toString());
      }) || {};
      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 ? 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