"use strict";

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

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

var _auth0React = require("@auth0/auth0-react");

var _clone = _interopRequireDefault(require("clone"));

var _formik = require("formik");

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

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

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

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

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

var yup = _interopRequireWildcard(require("yup"));

var _accountPage = _interopRequireDefault(require("../account-page"));

var userActions = _interopRequireWildcard(require("../../../actions/user"));

var _backLink = _interopRequireDefault(require("../back-link"));

var _formNavigationButtons = _interopRequireDefault(require("../form-navigation-buttons"));

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

var _constants = require("../../../util/constants");

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

var _user2 = require("../../../util/user");

var _withLoggedInUserSupport = _interopRequireDefault(require("../with-logged-in-user-support"));

var _placeEditor = _interopRequireDefault(require("./place-editor"));

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 {
  isMobile
} = _coreUtils.default.ui; // Styled components

const SaveButton = (0, _styledComponents.default)(_reactBootstrap.Button)`
  float: right;
`;
const BLANK_PLACE = { ..._user2.PLACE_TYPES.custom,
  address: '',
  name: ''
}; // Make space between place details and form buttons.

const Container = _styledComponents.default.div`
  margin-bottom: 100px;
`; // The form fields to validate.

const validationSchemaShape = {
  address: yup.string().required('Please set a location for this place'),
  name: yup.string().required('Please enter a name for this place')
};
/**
 * Lets the user edit the details (address, type, nickname)
 * of a new or existing favorite place.
 */

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

    _defineProperty(this, "_handleSave", async placeToSave => {
      // Update the icon for the place type.
      placeToSave.icon = _user2.PLACE_TYPES[placeToSave.type].icon; // Save changes to loggedInUser.

      const {
        placeIndex,
        saveUserPlace
      } = this.props;
      await saveUserPlace(placeToSave, placeIndex); // Return to previous location when done.

      (0, _ui.navigateBack)();
    });

    _defineProperty(this, "_getPlaceToEdit", user => {
      const {
        isNewPlace,
        placeIndex
      } = this.props;
      return isNewPlace ? BLANK_PLACE : user.savedLocations ? user.savedLocations[placeIndex] : null;
    });

    _defineProperty(this, "_getFullValidationSchema", (places, place) => {
      const otherPlaceNames = (place ? places.filter(pl => pl.name !== place.name) : places).map(pl => pl.name);
      const clonedSchemaShape = (0, _clone.default)(validationSchemaShape);
      clonedSchemaShape.name = yup.string().required('Please enter a name for this place').notOneOf(otherPlaceNames, 'You are already using this name for another place. Please enter a different name.');
      return yup.object(clonedSchemaShape);
    });
  }

  render() {
    const {
      isCreating,
      isNewPlace,
      loggedInUser
    } = this.props; // Get the places as shown (and not as retrieved from db), so that the index passed from URL applies
    // (indexes 0 and 1 are for Home and Work locations).

    const place = this._getPlaceToEdit(loggedInUser);

    const isFixed = place && (0, _user2.isHomeOrWork)(place);
    const isMobileView = isMobile();
    let heading;

    if (!place) {
      heading = 'Place not found';
    } else if (isNewPlace) {
      heading = 'Add a new place';
    } else if (isFixed) {
      heading = `Edit ${place.name}`;
    } else {
      heading = 'Edit place';
    }

    return /*#__PURE__*/_react.default.createElement(_accountPage.default, {
      subnav: !isCreating
    }, isMobileView && /*#__PURE__*/_react.default.createElement(_backLink.default, null), /*#__PURE__*/_react.default.createElement(_formik.Formik, {
      initialValues: (0, _clone.default)(place),
      onSubmit: this._handleSave,
      validateOnBlur: true // Avoid validating on change as it is annoying. Validating on blur is enough.
      ,
      validateOnChange: false,
      validationSchema: this._getFullValidationSchema(loggedInUser.savedLocations, place)
    }, // We pass the Formik props below to the components rendered so that individual controls
    // can be wired to be managed by Formik.
    props => {
      return /*#__PURE__*/_react.default.createElement(_formik.Form, {
        noValidate: true
      }, /*#__PURE__*/_react.default.createElement("div", null, isMobileView && place && /*#__PURE__*/_react.default.createElement(SaveButton, {
        bsStyle: "primary",
        type: "submit"
      }, "Save"), /*#__PURE__*/_react.default.createElement(_styled.PageHeading, null, heading)), /*#__PURE__*/_react.default.createElement(Container, null, place ? /*#__PURE__*/_react.default.createElement(_placeEditor.default, props) : /*#__PURE__*/_react.default.createElement("p", null, "Sorry, the requested place was not found.")), !isMobileView && /*#__PURE__*/_react.default.createElement(_formNavigationButtons.default, {
        backButton: {
          onClick: _ui.navigateBack,
          text: 'Back'
        },
        okayButton: {
          text: 'Save',
          type: 'submit'
        }
      }));
    }));
  }

} // connect to the redux store


const mapStateToProps = (state, ownProps) => {
  const {
    params,
    path
  } = ownProps.match;
  const placeIndex = params.id;
  return {
    isCreating: path.startsWith(_constants.CREATE_ACCOUNT_PLACES_PATH),
    isNewPlace: placeIndex === 'new',
    loggedInUser: state.user.loggedInUser,
    placeIndex
  };
};

const mapDispatchToProps = {
  saveUserPlace: userActions.saveUserPlace
};

var _default = (0, _withLoggedInUserSupport.default)((0, _auth0React.withAuthenticationRequired)((0, _reactRedux.connect)(mapStateToProps, mapDispatchToProps)(FavoritePlaceScreen), _ui.RETURN_TO_CURRENT_ROUTE), true);

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

//# sourceMappingURL=favorite-place-screen.js