"use strict";

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

require("core-js/modules/web.dom.iterable");

var _react = _interopRequireWildcard(require("react"));

var _reactRedux = require("react-redux");

var _reactIntl = require("react-intl");

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

var _viewer = require("../../util/viewer");

var _icon = _interopRequireDefault(require("../util/icon"));

var _api = require("../../actions/api");

var _ui = require("../../actions/ui");

var _styled = require("./styled");

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

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

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; }

class RouteDetails extends _react.Component {
  constructor(...args) {
    super(...args);

    _defineProperty(this, "componentDidMount", () => {
      const {
        getVehiclePositionsForRoute,
        pattern,
        route
      } = this.props;

      if (!route.vehicles) {
        getVehiclePositionsForRoute(route.id);
      }

      if (!(pattern === null || pattern === void 0 ? void 0 : pattern.stops)) {
        this.getStops();
      }
    });

    _defineProperty(this, "componentDidUpdate", prevProps => {
      var _prevProps$pattern, _this$props$pattern;

      if (((_prevProps$pattern = prevProps.pattern) === null || _prevProps$pattern === void 0 ? void 0 : _prevProps$pattern.id) !== ((_this$props$pattern = this.props.pattern) === null || _this$props$pattern === void 0 ? void 0 : _this$props$pattern.id)) {
        this.getStops();
      }
    });

    _defineProperty(this, "getStops", () => {
      const {
        findStopsForPattern,
        pattern,
        route
      } = this.props;

      if (pattern && route) {
        findStopsForPattern({
          patternId: pattern.id,
          routeId: route.id
        });
      }
    });

    _defineProperty(this, "_headSignButtonClicked", e => {
      const {
        target
      } = e;
      const {
        value: id
      } = target;
      const {
        route,
        setViewedRoute
      } = this.props;
      setViewedRoute({
        patternId: id,
        routeId: route.id
      });
    });

    _defineProperty(this, "_stopLinkClicked", stopId => {
      const {
        setViewedStop
      } = this.props;
      setViewedStop({
        stopId
      });
    });
  }

  render() {
    var _pattern$stops;

    const {
      intl,
      operator,
      pattern,
      route,
      setHoveredStop,
      viewedRoute
    } = this.props;
    const {
      agency,
      patterns,
      url
    } = route;
    const {
      backgroundColor: routeColor
    } = (0, _viewer.getColorAndNameFromRoute)(operator, route);
    const headsigns = patterns && Object.entries(patterns).map(pattern => {
      var _pattern$1$geometry;

      return {
        geometryLength: (_pattern$1$geometry = pattern[1].geometry) === null || _pattern$1$geometry === void 0 ? void 0 : _pattern$1$geometry.length,
        headsign: (0, _viewer.extractHeadsignFromPattern)(pattern[1]),
        id: pattern[0]
      };
    }) // Remove duplicate headsigns. Using a reducer means that the first pattern
    // with a specific headsign is the accepted one. TODO: is this good behavior?
    .reduce((prev, cur) => {
      const amended = prev;
      const alreadyExistingIndex = prev.findIndex(h => h.headsign === cur.headsign); // If the item we're replacing has less geometry, replace it!

      if (alreadyExistingIndex >= 0) {
        // Only replace if new pattern has greater geometry
        if (amended[alreadyExistingIndex].geometryLength < cur.geometryLength) {
          amended[alreadyExistingIndex] = cur;
        }
      } else {
        amended.push(cur);
      }

      return amended;
    }, []).sort((a, b) => {
      var _route$vehicles, _route$vehicles2;

      // sort by number of vehicles on that pattern
      const aVehicleCount = (_route$vehicles = route.vehicles) === null || _route$vehicles === void 0 ? void 0 : _route$vehicles.filter(vehicle => vehicle.patternId === a.id).length;
      const bVehicleCount = (_route$vehicles2 = route.vehicles) === null || _route$vehicles2 === void 0 ? void 0 : _route$vehicles2.filter(vehicle => vehicle.patternId === b.id).length; // if both have the same count, sort by pattern geometry length

      if (aVehicleCount === bVehicleCount) {
        return b.geometryLength - a.geometryLength;
      }

      return bVehicleCount - aVehicleCount;
    }); // if no pattern is set, we are in the routeRow

    return /*#__PURE__*/_react.default.createElement(_styled.Container, {
      full: pattern != null
    }, /*#__PURE__*/_react.default.createElement(_styled.RouteNameContainer, null, /*#__PURE__*/_react.default.createElement(_styled.LogoLinkContainer, null, agency && /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "components.RouteDetails.operatedBy",
      values: {
        agencyName: agency.name
      }
    }), url && /*#__PURE__*/_react.default.createElement("a", {
      href: url,
      style: {
        whiteSpace: 'nowrap'
      },
      target: "_blank"
    }, /*#__PURE__*/_react.default.createElement(_icon.default, {
      type: "link"
    }), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "components.RouteDetails.moreDetails"
    })))), /*#__PURE__*/_react.default.createElement(_styled.PatternContainer, null, /*#__PURE__*/_react.default.createElement("h4", null, /*#__PURE__*/_react.default.createElement("label", {
      htmlFor: "headsign-selector",
      id: "headsign-selector-label"
    }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "components.RouteDetails.stopsTo"
    }))), headsigns && /*#__PURE__*/_react.default.createElement("select", {
      id: "headsign-selector",
      name: "headsigns",
      onBlur: this._headSignButtonClicked,
      onChange: this._headSignButtonClicked,
      value: viewedRoute === null || viewedRoute === void 0 ? void 0 : viewedRoute.patternId
    }, !(viewedRoute === null || viewedRoute === void 0 ? void 0 : viewedRoute.patternId) && /*#__PURE__*/_react.default.createElement("option", {
      value: ""
    }, intl.formatMessage({
      id: 'components.RouteDetails.selectADirection'
    })), headsigns.map(h => /*#__PURE__*/_react.default.createElement("option", {
      key: h.id,
      value: h.id
    }, h.headsign)))), pattern && /*#__PURE__*/_react.default.createElement(_styled.StopContainer, {
      onMouseLeave: () => setHoveredStop(null)
    }, pattern === null || pattern === void 0 ? void 0 : (_pattern$stops = pattern.stops) === null || _pattern$stops === void 0 ? void 0 : _pattern$stops.map(stop => /*#__PURE__*/_react.default.createElement(_styled.Stop, {
      key: stop.id,
      onClick: () => this._stopLinkClicked(stop.id),
      onFocus: () => setHoveredStop(stop.id),
      onMouseOver: () => setHoveredStop(stop.id),
      routeColor: routeColor.includes('ffffff') ? '#333' : routeColor
    }, stop.name))));
  }

} // connect to redux store


_defineProperty(RouteDetails, "propTypes", {
  className: _propTypes.default.string,
  findStopsForPattern: _api.findStopsForPattern.type,
  operator: _propTypes.default.shape({
    defaultRouteColor: _propTypes.default.string,
    defaultRouteTextColor: _propTypes.default.string,
    longNameSplitter: _propTypes.default.string
  }),
  // There are more items in pattern and route, but none mandatory
  pattern: _propTypes.default.shape({
    id: _propTypes.default.string
  }),
  route: _propTypes.default.shape({
    id: _propTypes.default.string
  }),
  setHoveredStop: _ui.setHoveredStop.type,
  setViewedRoute: _ui.setViewedRoute.type
});

const mapStateToProps = (state, ownProps) => {
  return {
    viewedRoute: state.otp.ui.viewedRoute
  };
};

const mapDispatchToProps = {
  findStopsForPattern: _api.findStopsForPattern,
  getVehiclePositionsForRoute: _api.getVehiclePositionsForRoute,
  setHoveredStop: _ui.setHoveredStop,
  setViewedRoute: _ui.setViewedRoute,
  setViewedStop: _ui.setViewedStop
};

var _default = (0, _reactRedux.connect)(mapStateToProps, mapDispatchToProps)((0, _reactIntl.injectIntl)(RouteDetails));

exports.default = _default;
module.exports = exports.default;

//# sourceMappingURL=route-details.js