"use strict";

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

var _react = require("react");

var _reactMapGl = _interopRequireWildcard(require("react-map-gl"));

var _reactDimensions = _interopRequireDefault(require("react-dimensions"));

var _core = require("@emotion/core");

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

var _createRef = _interopRequireDefault(require("create-react-ref/lib/createRef"));

var _reactMapGlGeocoder = _interopRequireDefault(require("react-map-gl-geocoder"));

require("mapbox-gl/dist/mapbox-gl.css");

var _lodash = require("lodash");

var _mapboxgl = _interopRequireDefault(require("./mapboxgl"));

var _index = require("../_Themes/index");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _templateObject2() {
  var data = _taggedTemplateLiteral(["\n  position: absolute;\n  left: 0;\n  z-index: 1;\n"]);

  _templateObject2 = function _templateObject2() {
    return data;
  };

  return data;
}

function _templateObject() {
  var data = _taggedTemplateLiteral(["\n  margin: 0 auto;\n  padding: 0;\n  width: 100%;\n  height: 100%;\n"]);

  _templateObject = function _templateObject() {
    return data;
  };

  return data;
}

function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }

var MAPBOX_TOKEN = _index.MapGLResources.MAPBOX_TOKEN,
    CIVIC_LIGHT = _index.MapGLResources.CIVIC_LIGHT,
    CIVIC_DARK = _index.MapGLResources.CIVIC_DARK,
    CIVIC_PENCIL = _index.MapGLResources.CIVIC_PENCIL,
    DISASTER_GAME = _index.MapGLResources.DISASTER_GAME;
var mapWrapper = (0, _core.css)(_templateObject());
var navControl = (0, _core.css)(_templateObject2());

var BaseMap = function (_Component) {
  _inherits(BaseMap, _Component);

  function BaseMap(props) {
    var _this;

    _classCallCheck(this, BaseMap);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(BaseMap).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "onHover", function (_ref) {
      var object = _ref.object,
          x = _ref.x,
          y = _ref.y;

      _this.setState({
        tooltipInfo: object,
        x: x,
        y: y
      });
    });

    _defineProperty(_assertThisInitialized(_this), "onViewportChange", function (viewport) {
      _this.setState(function (prevState) {
        return {
          viewport: _objectSpread({}, prevState.viewport, viewport)
        };
      });
    });

    _this.state = {
      viewport: {
        longitude: props.initialLongitude,
        latitude: props.initialLatitude,
        zoom: props.initialZoom,
        minZoom: props.minZoom,
        maxZoom: props.maxZoom,
        pitch: props.initialPitch,
        bearing: 0,
        scrollZoom: true
      },
      tooltipInfo: null,
      x: null,
      y: null,
      mounted: false
    };
    _this.mapRef = (0, _createRef["default"])();
    return _this;
  }

  _createClass(BaseMap, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.setState({
        mounted: true
      });
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(props) {
      var updateViewport = props.updateViewport;

      if (updateViewport) {
        var updatedViewportProps = {
          zoom: props.initialZoom,
          pitch: props.initialPitch,
          longitude: props.initialLongitude,
          latitude: props.initialLatitude
        };
        Object.keys(updatedViewportProps).forEach(function (key) {
          if (updatedViewportProps[key] == null) {
            delete updatedViewportProps[key];
          }
        });
        this.setState(function (prevState) {
          return {
            viewport: _objectSpread({}, prevState.viewport, updatedViewportProps)
          };
        });
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var previousMapboxData = prevProps.mapboxData,
          previousMapboxLayerOptions = prevProps.mapboxLayerOptions;
      var _this$props = this.props,
          mapboxData = _this$props.mapboxData,
          mapboxDataId = _this$props.mapboxDataId,
          mapboxLayerOptions = _this$props.mapboxLayerOptions,
          mapboxLayerId = _this$props.mapboxLayerId;

      if (!(0, _lodash.isEqual)(previousMapboxData, mapboxData)) {
        var map = this.mapRef.current.getMap();
        map.getSource(mapboxDataId).setData(mapboxData);
      }

      if (!(0, _lodash.isEqual)(previousMapboxLayerOptions, mapboxLayerOptions)) {
        var _map = this.mapRef.current.getMap();

        var updatedProperties = Object.keys(mapboxLayerOptions).filter(function (m) {
          return !(0, _lodash.isEqual)(previousMapboxLayerOptions[m], mapboxLayerOptions[m]);
        });
        updatedProperties.forEach(function (p) {
          return _map.setPaintProperty(mapboxLayerId, p, mapboxLayerOptions[p]);
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$state = this.state,
          viewport = _this$state.viewport,
          tooltipInfo = _this$state.tooltipInfo,
          x = _this$state.x,
          y = _this$state.y,
          mounted = _this$state.mounted;
      var _this$props2 = this.props,
          height = _this$props2.height,
          containerHeight = _this$props2.containerHeight,
          containerWidth = _this$props2.containerWidth,
          civicMapStyle = _this$props2.civicMapStyle,
          mapboxToken = _this$props2.mapboxToken,
          navigation = _this$props2.navigation,
          geocoder = _this$props2.geocoder,
          locationMarker = _this$props2.locationMarker,
          geocoderOptions = _this$props2.geocoderOptions,
          geocoderOnChange = _this$props2.geocoderOnChange,
          mapGLOptions = _this$props2.mapGLOptions,
          children = _this$props2.children,
          useContainerHeight = _this$props2.useContainerHeight,
          onBaseMapClick = _this$props2.onBaseMapClick,
          mapboxData = _this$props2.mapboxData,
          mapboxDataId = _this$props2.mapboxDataId,
          mapboxLayerType = _this$props2.mapboxLayerType,
          mapboxLayerOptions = _this$props2.mapboxLayerOptions,
          mapboxLayerId = _this$props2.mapboxLayerId,
          locationMarkerCoord = _this$props2.locationMarkerCoord,
          animate = _this$props2.animate,
          animationDuration = _this$props2.animationDuration,
          scaleBar = _this$props2.scaleBar,
          scaleBarOptions = _this$props2.scaleBarOptions,
          sharedViewport = _this$props2.sharedViewport,
          onSharedViewportChange = _this$props2.onSharedViewportChange;
      viewport.width = containerWidth || 500;
      viewport.height = useContainerHeight ? containerHeight : height;

      var childrenLayers = _react.Children.map(children, function (child) {
        var layerViewport = sharedViewport ? _objectSpread({}, viewport, sharedViewport) : viewport;
        return (0, _react.cloneElement)(child, {
          viewport: layerViewport,
          tooltipInfo: tooltipInfo,
          x: x,
          y: y,
          onHover: function onHover(info) {
            return _this2.onHover(info);
          }
        });
      });

      var onMapLoad = function onMapLoad() {
        var map = _this2.mapRef.current.getMap();

        if (scaleBar) {
          map.addControl(new _mapboxgl["default"].ScaleControl({
            maxWidth: scaleBarOptions.maxWidth,
            unit: scaleBarOptions.units
          }));
        }

        if (!mapboxData || !mapboxLayerType || !mapboxLayerOptions) return;
        map.addSource(mapboxDataId, {
          type: "geojson",
          data: mapboxData
        });
        map.addLayer({
          id: mapboxLayerId,
          type: mapboxLayerType,
          source: mapboxDataId,
          paint: mapboxLayerOptions
        }, "waterway-label");
      };

      var baseMapboxStyleURL = CIVIC_LIGHT;

      if (civicMapStyle === "dark") {
        baseMapboxStyleURL = CIVIC_DARK;
      } else if (civicMapStyle === "pencil") {
        baseMapboxStyleURL = CIVIC_PENCIL;
      } else if (civicMapStyle === "disaster-game") {
        baseMapboxStyleURL = DISASTER_GAME;
      }

      var animationProps = !animate ? {} : {
        transitionDuration: animationDuration,
        transitionInterpolator: new _reactMapGl.FlyToInterpolator()
      };
      var finalViewport = sharedViewport ? _objectSpread({}, viewport, sharedViewport, {
        height: height,
        width: containerWidth
      }) : viewport;
      return (0, _core.jsx)("div", {
        css: mapWrapper
      }, (0, _core.jsx)(_reactMapGl["default"], _extends({
        className: "MapGL"
      }, finalViewport, animationProps, {
        mapStyle: baseMapboxStyleURL,
        mapboxApiAccessToken: mapboxToken,
        onViewportChange: function onViewportChange(newViewport) {
          if (onSharedViewportChange) {
            onSharedViewportChange(newViewport);
          } else {
            _this2.onViewportChange(newViewport);
          }
        },
        ref: this.mapRef
      }, mapGLOptions, {
        onClick: onBaseMapClick,
        onLoad: onMapLoad
      }), (0, _core.jsx)("div", {
        css: navControl
      }, navigation && (0, _core.jsx)(_reactMapGl.NavigationControl, null)), locationMarker && (0, _core.jsx)(_reactMapGl.Marker, {
        latitude: locationMarkerCoord.latitude,
        longitude: locationMarkerCoord.longitude,
        offsetLeft: -20,
        offsetTop: -10
      }, (0, _core.jsx)("span", {
        role: "img",
        "aria-label": "star"
      }, "\u274C")), geocoder && mounted && (0, _core.jsx)(_reactMapGlGeocoder["default"], {
        mapRef: {
          current: this.mapRef.current
        },
        mapboxApiAccessToken: mapboxToken,
        onViewportChange: function onViewportChange(newViewport) {
          _this2.onViewportChange(newViewport);

          !!geocoderOnChange && geocoderOnChange(newViewport);
        },
        options: _objectSpread({}, geocoderOptions)
      }), childrenLayers));
    }
  }]);

  return BaseMap;
}(_react.Component);

BaseMap.propTypes = {
  initialLongitude: _propTypes["default"].number,
  initialLatitude: _propTypes["default"].number,
  initialZoom: _propTypes["default"].number,
  minZoom: _propTypes["default"].number,
  maxZoom: _propTypes["default"].number,
  initialPitch: _propTypes["default"].number,
  height: _propTypes["default"].number,
  containerHeight: _propTypes["default"].number,
  containerWidth: _propTypes["default"].number,
  mapboxToken: _propTypes["default"].string,
  civicMapStyle: _propTypes["default"].oneOf(["light", "dark", "pencil", "disaster-game"]),
  navigation: _propTypes["default"].bool,
  locationMarker: _propTypes["default"].bool,
  locationMarkerCoord: _propTypes["default"].shape({
    latitude: _propTypes["default"].number,
    longitude: _propTypes["default"].number
  }),
  geocoder: _propTypes["default"].bool,
  geocoderOptions: _propTypes["default"].shape({}),
  geocoderOnChange: _propTypes["default"].func,
  mapGLOptions: _propTypes["default"].shape({}),
  children: _propTypes["default"].node,
  useContainerHeight: _propTypes["default"].bool,
  updateViewport: _propTypes["default"].bool,
  animate: _propTypes["default"].bool,
  animationDuration: _propTypes["default"].number,
  onBaseMapClick: _propTypes["default"].func,
  mapboxDataId: _propTypes["default"].string,
  mapboxData: _propTypes["default"].shape({
    type: _propTypes["default"].string,
    features: _propTypes["default"].arrayOf(_propTypes["default"].shape({}))
  }),
  mapboxLayerType: _propTypes["default"].string,
  mapboxLayerId: _propTypes["default"].string,
  mapboxLayerOptions: _propTypes["default"].shape({}),
  scaleBar: _propTypes["default"].bool,
  scaleBarOptions: _propTypes["default"].shape({
    maxWidth: _propTypes["default"].number,
    units: _propTypes["default"].string
  }),
  sharedViewport: _propTypes["default"].shape({}),
  onSharedViewportChange: _propTypes["default"].func
};
BaseMap.defaultProps = {
  mapboxToken: MAPBOX_TOKEN,
  navigation: true,
  geocoder: false,
  useContainerHeight: false,
  updateViewport: true,
  animate: false,
  initialLongitude: -122.6765,
  initialLatitude: 45.5231,
  initialZoom: 9.5,
  minZoom: 6,
  maxZoom: 20,
  initialPitch: 0,
  height: 500,
  locationMarkerCoord: {
    latitude: 0,
    longitude: 0
  },
  animationDuration: 1000,
  scaleBar: false
};

var _default = (0, _reactDimensions["default"])()(BaseMap);

exports["default"] = _default;