"use strict";

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

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

var _coreUtils = _interopRequireDefault(require("@opentripplanner/core-utils"));

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

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

var _reactLoadingSkeleton = _interopRequireWildcard(require("react-loading-skeleton"));

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

var _narrative = require("../../actions/narrative");

var uiActions = _interopRequireWildcard(require("../../actions/ui"));

var _contexts = require("../../util/contexts");

var _state = require("../../util/state");

var _narrativeItinerariesErrors = _interopRequireDefault(require("./narrative-itineraries-errors"));

var _narrativeItinerariesHeader = _interopRequireDefault(require("./narrative-itineraries-header"));

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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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

const {
  ItineraryView
} = uiActions;

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

    _defineProperty(this, "state", {
      showingErrors: false
    });

    _defineProperty(this, "_setActiveLeg", (index, leg) => {
      const {
        activeLeg,
        setActiveLeg,
        setItineraryView
      } = this.props;
      const isSameLeg = activeLeg === index;

      if (isSameLeg) {
        // If clicking on the same leg again, reset it to null,
        // and show the full itinerary (both desktop and mobile view)
        setActiveLeg(null, null);
        setItineraryView(ItineraryView.FULL);
      } else {
        // Focus on the newly selected leg.
        setActiveLeg(index, leg);
        setItineraryView(ItineraryView.LEG);
      }
    });

    _defineProperty(this, "_toggleDetailedItinerary", () => {
      const {
        setActiveLeg,
        setItineraryView,
        showDetails
      } = this.props;
      const newView = showDetails ? ItineraryView.LIST : ItineraryView.FULL;
      setItineraryView(newView); // Reset the active leg.

      setActiveLeg(null, null);
    });

    _defineProperty(this, "_onSortChange", evt => {
      const {
        value: type
      } = evt.target;
      const {
        sort,
        updateItineraryFilter
      } = this.props;
      updateItineraryFilter({
        sort: { ...sort,
          type
        }
      });
    });

    _defineProperty(this, "_onSortDirChange", () => {
      const {
        sort,
        updateItineraryFilter
      } = this.props;
      const direction = sort.direction === 'ASC' ? 'DESC' : 'ASC';
      updateItineraryFilter({
        sort: { ...sort,
          direction
        }
      });
    });

    _defineProperty(this, "_onViewAllOptions", () => {
      if (this.props.itineraryIsExpanded) {
        this._toggleDetailedItinerary();
      } else {
        this._toggleShowErrors();
      }
    });

    _defineProperty(this, "_toggleShowErrors", () => {
      this.setState({
        showingErrors: !this.state.showingErrors
      });
    });

    _defineProperty(this, "_renderLoadingDivs", () => {
      const {
        itineraries,
        modes,
        pending
      } = this.props;
      const {
        showingErrors
      } = this.state;
      if (!pending || showingErrors) return null; // Construct loading divs as placeholders while all itineraries load.

      const count = modes.combinations ? modes.combinations.length - itineraries.length : 0;
      return Array.from({
        length: count
      }, (v, i) => /*#__PURE__*/_react.default.createElement("div", {
        className: "option default-itin",
        key: i
      }, /*#__PURE__*/_react.default.createElement(_reactLoadingSkeleton.SkeletonTheme, {
        color: "#ddd",
        highlightColor: "#eee"
      }, /*#__PURE__*/_react.default.createElement(_reactLoadingSkeleton.default, {
        count: 3
      }))));
    });
  }

  render() {
    const {
      activeItinerary,
      activeLeg,
      activeSearch,
      activeStep,
      containerStyle,
      errorMessages,
      errors,
      itineraries,
      itineraryIsExpanded,
      pending,
      realtimeEffects,
      setActiveItinerary,
      setActiveStep,
      setVisibleItinerary,
      showDetails,
      sort,
      timeFormat,
      useRealtime,
      visibleItinerary
    } = this.props;
    const {
      ItineraryBody,
      LegIcon
    } = this.context;
    const {
      showingErrors
    } = this.state;
    if (!activeSearch) return null;
    const showRealtimeAnnotation = realtimeEffects.isAffectedByRealtimeData && (realtimeEffects.exceedsThreshold || realtimeEffects.routesDiffer || !useRealtime);
    return /*#__PURE__*/_react.default.createElement("div", {
      className: "options itinerary",
      style: containerStyle
    }, /*#__PURE__*/_react.default.createElement(_narrativeItinerariesHeader.default, {
      errors: errors,
      itineraries: itineraries,
      itineraryIsExpanded: itineraryIsExpanded,
      onSortChange: this._onSortChange,
      onSortDirChange: this._onSortDirChange,
      onToggleShowErrors: this._toggleShowErrors,
      onViewAllOptions: this._onViewAllOptions,
      pending: pending,
      showingErrors: showingErrors,
      sort: sort
    }), /*#__PURE__*/_react.default.createElement("div", {
      // FIXME: Change to a ul with li children?
      className: "list",
      style: {
        flexGrow: '1',
        overflowY: 'auto'
      }
    }, showingErrors || itineraries.length === 0 ? /*#__PURE__*/_react.default.createElement(_narrativeItinerariesErrors.default, {
      errorMessages: errorMessages,
      errors: errors
    }) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, itineraries.map((itinerary, index) => {
      const active = index === activeItinerary; // Hide non-active itineraries.

      if (!active && itineraryIsExpanded) return null;
      return /*#__PURE__*/_react.default.createElement(ItineraryBody, {
        active: active,
        activeLeg: activeLeg,
        activeStep: activeStep,
        expanded: showDetails,
        index: index,
        itinerary: itinerary,
        key: index,
        LegIcon: LegIcon,
        onClick: active ? this._toggleDetailedItinerary : undefined,
        routingType: "ITINERARY",
        setActiveItinerary: setActiveItinerary,
        setActiveLeg: this._setActiveLeg,
        setActiveStep: setActiveStep,
        setVisibleItinerary: setVisibleItinerary,
        showRealtimeAnnotation: showRealtimeAnnotation,
        sort: sort,
        timeFormat: timeFormat,
        visibleItinerary: visibleItinerary
      });
    }), this._renderLoadingDivs())));
  }

} // connect to the redux store


_defineProperty(NarrativeItineraries, "propTypes", {
  activeItinerary: _propTypes.default.number,
  containerStyle: _propTypes.default.object,
  itineraries: _propTypes.default.array,
  pending: _propTypes.default.bool,
  setActiveItinerary: _propTypes.default.func,
  setActiveLeg: _propTypes.default.func,
  setActiveStep: _propTypes.default.func,
  setItineraryView: _propTypes.default.func,
  setUseRealtimeResponse: _propTypes.default.func,
  useRealtime: _propTypes.default.bool
});

_defineProperty(NarrativeItineraries, "contextType", _contexts.ComponentContext);

const mapStateToProps = (state, ownProps) => {
  const activeSearch = (0, _state.getActiveSearch)(state);
  const activeItinerary = activeSearch && activeSearch.activeItinerary;
  const {
    errorMessages,
    modes
  } = state.otp.config;
  const {
    sort
  } = state.otp.filter;
  const pending = activeSearch ? Boolean(activeSearch.pending) : false;
  const itineraries = (0, _state.getActiveItineraries)(state);
  const realtimeEffects = (0, _state.getRealtimeEffects)(state);
  const useRealtime = state.otp.useRealtime;

  const urlParams = _coreUtils.default.query.getUrlParams();

  const itineraryView = urlParams.ui_itineraryView || ItineraryView.LIST;
  const showDetails = itineraryView === ItineraryView.FULL || itineraryView === ItineraryView.LEG || itineraryView === ItineraryView.LEG_HIDDEN;
  const itineraryIsExpanded = activeItinerary !== undefined && activeItinerary !== null && showDetails;
  return {
    // swap out realtime itineraries with non-realtime depending on boolean
    activeItinerary,
    activeLeg: activeSearch && activeSearch.activeLeg,
    activeSearch,
    activeStep: activeSearch && activeSearch.activeStep,
    errorMessages,
    errors: (0, _state.getResponsesWithErrors)(state),
    itineraries,
    itineraryIsExpanded,
    itineraryView,
    // use a key so that the NarrativeItineraries component and its state is
    // reset each time a new search is shown
    key: state.otp.activeSearchId,
    modes,
    pending,
    realtimeEffects,
    showDetails,
    sort,
    timeFormat: _coreUtils.default.time.getTimeFormat(state.otp.config),
    useRealtime,
    visibleItinerary: (0, _state.getVisibleItineraryIndex)(state)
  };
};

const mapDispatchToProps = (dispatch, ownProps) => {
  // FIXME: update signature of these methods,
  // so that only one argument is passed,
  // e.g. setActiveLeg({ index, leg })
  return {
    setActiveItinerary: payload => dispatch((0, _narrative.setActiveItinerary)(payload)),
    // FIXME
    setActiveLeg: (index, leg) => {
      dispatch((0, _narrative.setActiveLeg)({
        index,
        leg
      }));
    },
    // FIXME
    setActiveStep: (index, step) => {
      dispatch((0, _narrative.setActiveStep)({
        index,
        step
      }));
    },
    setItineraryView: payload => dispatch(uiActions.setItineraryView(payload)),
    setUseRealtimeResponse: payload => dispatch((0, _narrative.setUseRealtimeResponse)(payload)),
    setVisibleItinerary: payload => dispatch((0, _narrative.setVisibleItinerary)(payload)),
    updateItineraryFilter: payload => dispatch((0, _narrative.updateItineraryFilter)(payload))
  };
};

var _default = (0, _reactRedux.connect)(mapStateToProps, mapDispatchToProps)(NarrativeItineraries);

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

//# sourceMappingURL=narrative-itineraries.js