"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 _formik = require("formik");

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

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

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

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

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

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

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

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

var _existingAccountDisplay = _interopRequireDefault(require("./existing-account-display"));

var _newAccountWizard = _interopRequireDefault(require("./new-account-wizard"));

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

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

// The validation schema for the form fields.
const validationSchema = yup.object({
  email: yup.string().email(),
  hasConsentedToTerms: yup.boolean().oneOf([true], 'You must agree to the terms to continue.'),
  notificationChannel: yup.string().oneOf(['email', 'sms', 'none']),
  savedLocations: yup.array().of(yup.object({
    address: yup.string(),
    icon: yup.string(),
    type: yup.string()
  })),
  storeTripHistory: yup.boolean()
});
/**
 * This screen handles creating/updating OTP user account settings.
 */

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

    _defineProperty(this, "_updateUserPrefs", async (userData, silentOnSucceed = false) => {
      // TODO: Change state of Save button while the update action takes place.
      await this.props.createOrUpdateUser(userData, silentOnSucceed); // TODO: Handle UI feedback (currently an alert() dialog inside createOrUpdateUser).
    });

    _defineProperty(this, "_handleCreateNewUser", userData => {
      this._updateUserPrefs(userData, true);
    });

    _defineProperty(this, "_handleDeleteUser", evt => {
      const {
        auth0,
        deleteUser,
        loggedInUser
      } = this.props; // Avoid triggering onsubmit with formik (which would result in a save user
      // call).

      evt.preventDefault();

      if (confirm('Are you sure you would like to delete your user account? Once you do so, it cannot be recovered.')) {
        deleteUser(loggedInUser, auth0);
      }
    });

    _defineProperty(this, "_handleExit", () => {
      // On exit, route to default search route.
      this.props.routeTo('/');
    });

    _defineProperty(this, "_handleSaveAndExit", async userData => {
      await this._updateUserPrefs(userData);

      this._handleExit();
    });
  }

  // TODO: Update title bar during componentDidMount.
  render() {
    const {
      auth0,
      isCreating,
      itemId,
      loggedInUser,
      phoneFormatOptions,
      requestPhoneVerificationSms,
      verifyPhoneNumber
    } = this.props;
    return /*#__PURE__*/_react.default.createElement(_accountPage.default, {
      subnav: !isCreating
    }, /*#__PURE__*/_react.default.createElement(_formik.Formik // Force Formik to reload initialValues when we update them (e.g. user gets assigned an id).
    , {
      enableReinitialize: true,
      initialValues: loggedInUser,
      onSubmit: this._handleSaveAndExit // Avoid validating on change as it is annoying. Validating on blur is enough.
      ,
      validateOnBlur: true,
      validateOnChange: false,
      validationSchema: validationSchema
    }, // Formik props provide access to the current user data state and errors,
    // (in props.values, props.touched, props.errors)
    // and to its own blur/change/submit event handlers that automate the state.
    // We pass the Formik props below to the components rendered so that individual controls
    // can be wired to be managed by Formik.
    formikProps => {
      const DisplayComponent = isCreating ? _newAccountWizard.default : _existingAccountDisplay.default;
      return /*#__PURE__*/_react.default.createElement(_formik.Form, {
        noValidate: true
      }, /*#__PURE__*/_react.default.createElement(DisplayComponent, _extends({}, formikProps, {
        activePaneId: itemId,
        emailVerified: auth0.user.email_verified,
        loggedInUser: loggedInUser,
        onCancel: this._handleExit,
        onCreate: this._handleCreateNewUser,
        onDelete: this._handleDeleteUser,
        onRequestPhoneVerificationCode: requestPhoneVerificationSms,
        onSendPhoneVerificationCode: verifyPhoneNumber,
        phoneFormatOptions: phoneFormatOptions
      })));
    }));
  }

} // connect to the redux store


const mapStateToProps = (state, ownProps) => {
  const {
    params,
    url
  } = ownProps.match;
  const isCreating = url.startsWith(_constants.CREATE_ACCOUNT_PATH);
  const {
    step
  } = params;
  return {
    isCreating,
    itemId: step,
    loggedInUser: state.user.loggedInUser,
    phoneFormatOptions: state.otp.config.phoneFormatOptions
  };
};

const mapDispatchToProps = {
  createOrUpdateUser: userActions.createOrUpdateUser,
  deleteUser: userActions.deleteUser,
  requestPhoneVerificationSms: userActions.requestPhoneVerificationSms,
  routeTo: uiActions.routeTo,
  verifyPhoneNumber: userActions.verifyPhoneNumber
};

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

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

//# sourceMappingURL=user-account-screen.js