"use strict";

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

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

var _moment = _interopRequireDefault(require("moment"));

require("moment-timezone");

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

var _fromToLocationPicker = _interopRequireDefault(require("@opentripplanner/from-to-location-picker"));

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

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

var _reactBootstrap = require("react-bootstrap");

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

var _styledComponents = _interopRequireDefault(require("styled-components"));

var apiActions = _interopRequireWildcard(require("../../actions/api"));

var mapActions = _interopRequireWildcard(require("../../actions/map"));

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

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

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

var _ui2 = require("../../util/ui");

var _liveStopTimes = _interopRequireDefault(require("./live-stop-times"));

var _stopScheduleTable = _interopRequireDefault(require("./stop-schedule-table"));

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 {
  getTimeFormat,
  getUserTimezone,
  OTP_API_DATE_FORMAT
} = _coreUtils.default.time;
const defaultState = {
  date: (0, _moment.default)().format(OTP_API_DATE_FORMAT),
  scheduleView: false
}; // A scrollable container for the contents of the stop viewer body.

const Scrollable = _styledComponents.default.div`
  margin-right: -12px;
  overflow-y: auto;
  padding-right: 12px;
`; // Alert with custom styles

const StyledAlert = (0, _styledComponents.default)(_reactBootstrap.Alert)`
  /* 'clear: both' prevents the date selector from overlapping with the alert. */
  clear: both;
  margin: 10px 0;
  padding: 5px 10px;
  text-align: center;
`;

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

    _defineProperty(this, "state", defaultState);

    _defineProperty(this, "_backClicked", () => (0, _ui2.navigateBack)());

    _defineProperty(this, "_setLocationFromStop", locationType => {
      const {
        setLocation,
        stopData
      } = this.props;
      const location = {
        lat: stopData.lat,
        lon: stopData.lon,
        name: stopData.name
      };
      setLocation({
        location,
        locationType,
        reverseGeocode: true
      });
      this.setState({
        popupPosition: null
      });
    });

    _defineProperty(this, "_onClickPlanTo", () => this._setLocationFromStop('to'));

    _defineProperty(this, "_onClickPlanFrom", () => this._setLocationFromStop('from'));

    _defineProperty(this, "_toggleFavorite", () => {
      const {
        forgetStop,
        rememberStop,
        stopData
      } = this.props;
      if (this._isFavorite()) forgetStop(stopData.id);else rememberStop(stopData);
    });

    _defineProperty(this, "_findStopTimesForDate", date => {
      const {
        findStopTimesForStop,
        viewedStop
      } = this.props;
      findStopTimesForStop({
        date,
        stopId: viewedStop.stopId
      });
    });

    _defineProperty(this, "_toggleScheduleView", () => {
      const {
        date,
        scheduleView: isShowingScheduleView
      } = this.state; // If not currently showing schedule view, fetch schedules for current date.
      // Otherwise fetch next arrivals.

      this._findStopTimesForDate(!isShowingScheduleView ? date : null);

      this.setState({
        scheduleView: !isShowingScheduleView
      });
    });

    _defineProperty(this, "_isFavorite", () => this.props.stopData && this.props.favoriteStops.findIndex(s => s.id === this.props.stopData.id) !== -1);

    _defineProperty(this, "handleDateChange", evt => {
      const date = evt.target.value;

      this._findStopTimesForDate(date);

      this.setState({
        date
      });
    });

    _defineProperty(this, "_renderHeader", () => {
      const {
        hideBackButton,
        showUserSettings,
        stopData
      } = this.props;
      return /*#__PURE__*/_react.default.createElement("div", {
        className: "stop-viewer-header"
      }, !hideBackButton && /*#__PURE__*/_react.default.createElement("div", {
        className: "back-button-container"
      }, /*#__PURE__*/_react.default.createElement(_reactBootstrap.Button, {
        bsSize: "small",
        onClick: this._backClicked
      }, /*#__PURE__*/_react.default.createElement(_icon.default, {
        type: "arrow-left"
      }), "Back")), /*#__PURE__*/_react.default.createElement("div", {
        className: "header-text"
      }, stopData ? /*#__PURE__*/_react.default.createElement("span", null, stopData.name) : /*#__PURE__*/_react.default.createElement("span", null, "Loading Stop..."), showUserSettings ? /*#__PURE__*/_react.default.createElement(_reactBootstrap.Button, {
        bsSize: "large",
        bsStyle: "link",
        onClick: this._toggleFavorite,
        style: {
          color: this._isFavorite() ? 'yellow' : 'black',
          marginLeft: '5px',
          padding: 0
        }
      }, /*#__PURE__*/_react.default.createElement(_icon.default, {
        type: this._isFavorite() ? 'star' : 'star-o'
      })) : null), /*#__PURE__*/_react.default.createElement("div", {
        style: {
          clear: 'both'
        }
      }));
    });

    _defineProperty(this, "_renderControls", () => {
      const {
        homeTimezone,
        stopData
      } = this.props;
      const {
        scheduleView
      } = this.state;
      const userTimeZone = getUserTimezone();
      const inHomeTimezone = homeTimezone && homeTimezone === userTimeZone; // Rewrite stop ID to not include Agency prefix, if present
      // TODO: make this functionality configurable?

      let stopId;

      if (stopData && stopData.id) {
        stopId = stopData.id.includes(':') ? stopData.id.split(':')[1] : stopData.id;
      }

      let timezoneWarning;

      if (!inHomeTimezone) {
        const timezoneCode = (0, _moment.default)().tz(homeTimezone).format('z'); // Display a banner about the departure timezone if user's timezone is not the configured 'homeTimezone'
        // (e.g. cases where a user in New York looks at a schedule in Los Angeles).

        timezoneWarning = /*#__PURE__*/_react.default.createElement(StyledAlert, {
          bsStyle: "info"
        }, /*#__PURE__*/_react.default.createElement(_reactBootstrap.Glyphicon, {
          glyph: "info-sign"
        }), " Departure times are shown in ", /*#__PURE__*/_react.default.createElement("strong", null, timezoneCode), ".");
      }

      return /*#__PURE__*/_react.default.createElement("div", {
        style: {
          marginBottom: '10px'
        }
      }, /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement("b", null, "Stop ID"), ": ", stopId, /*#__PURE__*/_react.default.createElement("button", {
        className: "link-button pull-right",
        onClick: this._toggleScheduleView,
        style: {
          fontSize: 'small'
        }
      }, /*#__PURE__*/_react.default.createElement(_icon.default, {
        type: scheduleView ? 'clock-o' : 'calendar'
      }), ' ', "View ", scheduleView ? 'next arrivals' : 'schedule')), /*#__PURE__*/_react.default.createElement("b", null, "Plan a trip:"), /*#__PURE__*/_react.default.createElement(_fromToLocationPicker.default, {
        onFromClick: this._onClickPlanFrom,
        onToClick: this._onClickPlanTo
      }), scheduleView && /*#__PURE__*/_react.default.createElement("input", {
        className: "pull-right",
        onChange: this.handleDateChange,
        onKeyDown: this.props.onKeyDown,
        required: true,
        style: {
          border: 'none',
          outline: 'none',
          width: '125px'
        },
        type: "date",
        value: this.state.date
      }), timezoneWarning);
    });
  }

  componentDidMount() {
    // Load the viewed stop in the store when the Stop Viewer first mounts
    this.props.findStop({
      stopId: this.props.viewedStop.stopId
    });
  }

  componentDidUpdate(prevProps) {
    if (prevProps.viewedStop && this.props.viewedStop && prevProps.viewedStop.stopId !== this.props.viewedStop.stopId) {
      // Reset state to default if stop changes (i.e., show next arrivals).
      this.setState(defaultState);
      this.props.findStop({
        stopId: this.props.viewedStop.stopId
      });
    }
  }

  render() {
    const {
      autoRefreshStopTimes,
      findStopTimesForStop,
      homeTimezone,
      stopData,
      stopViewerArriving,
      stopViewerConfig,
      timeFormat,
      toggleAutoRefresh,
      transitOperators,
      viewedStop
    } = this.props;
    const {
      date,
      scheduleView
    } = this.state;
    const {
      showBlockIds
    } = stopViewerConfig;
    const hasStopTimesAndRoutes = !!(stopData && stopData.stopTimes && stopData.stopTimes.length > 0 && stopData.routes);
    let contents;

    if (!hasStopTimesAndRoutes) {
      contents = /*#__PURE__*/_react.default.createElement("div", null, "No stop times found for date.");
    } else if (scheduleView) {
      contents = /*#__PURE__*/_react.default.createElement(_stopScheduleTable.default, {
        date: date,
        homeTimezone: homeTimezone,
        showBlockIds: showBlockIds,
        stopData: stopData,
        timeFormat: timeFormat
      });
    } else {
      contents = /*#__PURE__*/_react.default.createElement(_liveStopTimes.default, {
        autoRefreshStopTimes: autoRefreshStopTimes,
        findStopTimesForStop: findStopTimesForStop,
        homeTimezone: homeTimezone,
        stopData: stopData,
        stopViewerArriving: stopViewerArriving,
        stopViewerConfig: stopViewerConfig,
        timeFormat: timeFormat,
        toggleAutoRefresh: toggleAutoRefresh,
        transitOperators: transitOperators,
        viewedStop: viewedStop
      });
    }

    return /*#__PURE__*/_react.default.createElement("div", {
      className: "stop-viewer"
    }, this._renderHeader(), stopData && /*#__PURE__*/_react.default.createElement("div", {
      className: "stop-viewer-body"
    }, this._renderControls(), /*#__PURE__*/_react.default.createElement(Scrollable, null, contents)));
  }

} // connect to redux store


_defineProperty(StopViewer, "propTypes", {
  hideBackButton: _propTypes.default.bool,
  stopData: _propTypes.default.object,
  viewedStop: _propTypes.default.object
});

const mapStateToProps = (state, ownProps) => {
  const showUserSettings = (0, _state.getShowUserSettings)(state);
  const stopViewerConfig = (0, _state.getStopViewerConfig)(state);
  return {
    autoRefreshStopTimes: state.otp.user.autoRefreshStopTimes,
    favoriteStops: state.otp.user.favoriteStops,
    homeTimezone: state.otp.config.homeTimezone,
    showUserSettings,
    stopData: state.otp.transitIndex.stops[state.otp.ui.viewedStop.stopId],
    stopViewerArriving: state.otp.config.language.stopViewerArriving,
    stopViewerConfig,
    timeFormat: getTimeFormat(state.otp.config),
    transitOperators: state.otp.config.transitOperators,
    viewedStop: state.otp.ui.viewedStop
  };
};

const mapDispatchToProps = {
  findStop: apiActions.findStop,
  findStopTimesForStop: apiActions.findStopTimesForStop,
  forgetStop: mapActions.forgetStop,
  rememberStop: mapActions.rememberStop,
  setLocation: mapActions.setLocation,
  setMainPanelContent: uiActions.setMainPanelContent,
  toggleAutoRefresh: uiActions.toggleAutoRefresh
};

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

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

//# sourceMappingURL=stop-viewer.js