"use strict";

exports.__esModule = true;
exports.default = PublicInfo;

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

var _styles = require("@mui/material/styles");

var _material = require("@mui/material");

var _Icon = _interopRequireDefault(require("@mui/material/Icon"));

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

var _core = require("@selfcommunity/core");

var _UserProfile = require("../../../constants/UserProfile");

var _classnames = _interopRequireDefault(require("classnames"));

var _lab = require("@mui/lab");

var _AdapterDateFns = _interopRequireDefault(require("@mui/lab/AdapterDateFns"));

var _UsernameTextField = _interopRequireDefault(require("../../../shared/UsernameTextField"));

var _useDeepCompareEffect = require("use-deep-compare-effect");

var _useThemeProps = _interopRequireDefault(require("@mui/material/styles/useThemeProps"));

const _excluded = ["id", "className", "fields"],
      _excluded2 = ["InputProps"];

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

const messages = (0, _reactIntl.defineMessages)({
  genderMale: {
    id: 'ui.userProfileEditPublicInfo.genderMale',
    defaultMessage: 'ui.userProfileEditPublicInfo.genderMale'
  },
  genderFemale: {
    id: 'ui.userProfileEditPublicInfo.genderFemale',
    defaultMessage: 'ui.userProfileEditPublicInfo.genderFemale'
  },
  genderUnspecified: {
    id: 'ui.userProfileEditPublicInfo.genderUnspecified',
    defaultMessage: 'ui.userProfileEditPublicInfo.genderUnspecified'
  }
});
const PREFIX = 'SCUserProfileEditSectionPublicInfo';
const classes = {
  root: `${PREFIX}-root`,
  field: `${PREFIX}-field`
};
const Root = (0, _styles.styled)(_material.Box, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  [`& .${classes.field}`]: {
    margin: theme.spacing(1, 0, 1, 0)
  },
  ['& .${classes.field} .MuiSelect-icon']: {
    right: theme.spacing(5)
  }
}));
const GENDERS = ['Male', 'Female', 'Unspecified'];

function PublicInfo(inProps) {
  // PROPS
  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: PREFIX
  });

  const {
    id = null,
    className = null,
    fields = [..._UserProfile.DEFAULT_FIELDS]
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // CONTEXT


  const scUserContext = (0, _core.useSCUser)(); // PREFERENCES

  const scPreferences = (0, _core.useSCPreferences)();
  const metadataDefinitions = (0, _react.useMemo)(() => {
    return JSON.parse(scPreferences.preferences[_core.SCPreferences.CONFIGURATIONS_USER_METADATA_DEFINITIONS].value);
  }, [scPreferences.preferences]); // STATE

  const [user, setUser] = (0, _react.useState)(scUserContext.user);
  const [error, setError] = (0, _react.useState)({});
  const [editing, setEditing] = (0, _react.useState)([]);
  const [saving, setSaving] = (0, _react.useState)([]); // INTL

  const intl = (0, _reactIntl.useIntl)(); // EFFECTS

  (0, _useDeepCompareEffect.useDeepCompareEffectNoCheck)(() => {
    setUser(scUserContext.user);
  }, [scUserContext.user]); // HANDLERS

  const handleEdit = field => {
    return event => {
      setEditing([...editing, field]);

      if (error[`${_core.StringUtils.camelCase(field)}Error`]) {
        delete error[`${_core.StringUtils.camelCase(field)}Error`];
        setError(error);
      }
    };
  };

  const handleSave = field => {
    return event => {
      if (user[field] === scUserContext.user[field]) {
        setEditing(editing.filter(f => f !== field));
        return;
      }

      setSaving([...saving, field]);

      _core.http.request({
        url: _core.Endpoints.UserPatch.url({
          id: user.id
        }),
        method: _core.Endpoints.UserPatch.method,
        data: {
          [field]: user[field]
        }
      }).then(res => {
        scUserContext.updateUser(res.data);
      }).catch(error => {
        setError(Object.assign({}, error, (0, _core.formatHttpError)(error)));
      }).then(() => {
        setEditing(editing.filter(f => f !== field));
        setSaving(saving.filter(f => f !== field));
      });
    };
  };

  const handleChange = event => {
    setUser(Object.assign({}, user, {
      [event.target.name]: event.target.value
    }));
  }; // RENDER


  const getMetadataProps = field => {
    if (!metadataDefinitions[field]) {
      return {};
    }

    const props = {};

    switch (metadataDefinitions[field].type) {
      case 'url':
        props.type = 'url';
        props.pattern = 'https://.*';
        props.size = '30';
        break;

      case 'email':
        props.type = 'email';
        break;

      case 'phone_number':
        props.type = 'tel';
        break;
    }

    return props;
  };

  const renderField = field => {
    const isEditing = editing.includes(field);
    const isSaving = saving.includes(field);

    const camelField = _core.StringUtils.camelCase(field);

    const _error = error !== null && error[`${camelField}Error`] && error[`${camelField}Error`].error;

    const component = {
      element: _material.TextField
    };
    let props = {
      InputProps: {
        endAdornment: /*#__PURE__*/_react.default.createElement(_material.InputAdornment, {
          position: "end"
        }, !isEditing ? /*#__PURE__*/_react.default.createElement(_material.IconButton, {
          onClick: handleEdit(field),
          edge: "end"
        }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "edit")) : isSaving ? /*#__PURE__*/_react.default.createElement(_material.CircularProgress, {
          size: 10
        }) : /*#__PURE__*/_react.default.createElement(_material.IconButton, {
          onClick: handleSave(field),
          edge: "end",
          color: user[field] === scUserContext.user[field] ? 'default' : 'primary'
        }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "check")))
      }
    };
    let content = null;

    switch (field) {
      case _core.SCUserFields.USERNAME:
        component.element = _UsernameTextField.default;
        break;

      case _core.SCUserFields.DATE_JOINED:
        return null;

      case _core.SCUserFields.DATE_OF_BIRTH:
        return /*#__PURE__*/_react.default.createElement(_lab.LocalizationProvider, {
          dateAdapter: _AdapterDateFns.default,
          key: field
        }, /*#__PURE__*/_react.default.createElement(_lab.DatePicker, {
          label: intl.formatMessage({
            id: `ui.userProfileInfo.${_core.StringUtils.camelCase(field)}`,
            defaultMessage: `ui.userProfileInfo.${field}`
          }),
          value: user[field],
          onChange: newValue => {
            setUser(Object.assign({}, user, {
              [field]: newValue.toJSON().split('T')[0]
            })); // FIX for ensuring API format
          },
          disableFuture: true,
          disabled: !isEditing || isSaving,
          renderInput: params => {
            const {
              InputProps
            } = params,
                  rest = _objectWithoutPropertiesLoose(params, _excluded2);

            InputProps.endAdornment = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, InputProps.endAdornment, props.InputProps.endAdornment);
            return /*#__PURE__*/_react.default.createElement(_material.TextField, _extends({}, rest, {
              className: classes.field,
              fullWidth: true,
              InputProps: InputProps
            }));
          }
        }));

      case _core.SCUserFields.BIO:
        props.multiline = true;
        break;

      case _core.SCUserFields.WEBSITE:
        props.type = 'url';
        props.pattern = 'https://.*';
        props.size = '30';
        break;

      case _core.SCUserFields.GENDER:
        props.select = true;
        content = GENDERS.map(gender => /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
          key: gender,
          value: gender
        }, intl.formatMessage(messages[`gender${gender}`])));
        break;

      default:
        props = Object.assign({}, props, getMetadataProps(field));
        break;
    }

    return /*#__PURE__*/_react.default.createElement(component.element, _extends({
      key: field
    }, props, {
      className: classes.field,
      name: field,
      fullWidth: true,
      label: intl.formatMessage({
        id: `ui.userProfileInfo.${camelField}`,
        defaultMessage: `ui.userProfileInfo.${field}`
      }),
      value: user[field] || '',
      onChange: handleChange,
      disabled: !isEditing || isSaving,
      error: _error,
      helperText: _error
    }), content);
  };

  if (fields.length === 0 || !user) {
    return null;
  }

  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    id: id,
    className: (0, _classnames.default)(classes.root, className)
  }, rest), fields.map(field => {
    return renderField(field);
  }));
}