"use strict";

var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");

require("core-js/modules/es.function.name");

require("core-js/modules/es.regexp.exec");

require("core-js/modules/es.string.split");

_Object$defineProperty(exports, "__esModule", {
  value: true
});

exports.default = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/extends"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/objectWithoutProperties"));

var _isArray = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/is-array"));

var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));

var _reduce = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/reduce"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/slicedToArray"));

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

var _styles = require("@material-ui/core/styles");

var _Button = _interopRequireDefault(require("@material-ui/core/Button"));

var _Dialog = _interopRequireDefault(require("@material-ui/core/Dialog"));

var _TextField = _interopRequireDefault(require("./TextField"));

var _IconButton = _interopRequireDefault(require("@material-ui/core/IconButton"));

var _Close = _interopRequireDefault(require("@material-ui/icons/Close"));

var _Collapse = _interopRequireDefault(require("@material-ui/core/Collapse"));

var _ExpandMore = _interopRequireDefault(require("@material-ui/icons/ExpandMore"));

var _Fade = _interopRequireDefault(require("@material-ui/core/Fade"));

var _dateFns = _interopRequireDefault(require("@date-io/date-fns"));

var _enUS = _interopRequireDefault(require("date-fns/locale/en-US"));

var _fr = _interopRequireDefault(require("date-fns/locale/fr"));

var _ptBR = _interopRequireDefault(require("date-fns/locale/pt-BR"));

var _es = _interopRequireDefault(require("date-fns/locale/es"));

var _pickers = require("@material-ui/pickers");

var _Accordion = _interopRequireDefault(require("@material-ui/core/Accordion"));

var _AccordionSummary = _interopRequireDefault(require("@material-ui/core/AccordionSummary"));

var _AccordionDetails = _interopRequireDefault(require("@material-ui/core/AccordionDetails"));

var _DialogActions = _interopRequireDefault(require("@material-ui/core/DialogActions"));

var _DialogContent = _interopRequireDefault(require("@material-ui/core/DialogContent"));

var _DialogContentText = _interopRequireDefault(require("@material-ui/core/DialogContentText"));

var _DialogTitle = _interopRequireDefault(require("@material-ui/core/DialogTitle"));

var _MoreVert = _interopRequireDefault(require("@material-ui/icons/MoreVert"));

var _Menu = _interopRequireDefault(require("@material-ui/core/Menu"));

var _MenuItem = _interopRequireDefault(require("@material-ui/core/MenuItem"));

var _core = require("@material-ui/core");

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

var _cloneDeep = _interopRequireDefault(require("clone-deep"));

var _FeatureHeader = _interopRequireDefault(require("../internal/FeatureHeader"));

var _MediaCarousel = _interopRequireDefault(require("./MediaCarousel"));

var _helpers = require("../utils/helpers");

var _get_set = require("../utils/get_set");

var _Field = _interopRequireDefault(require("./Field"));

// @flow
var m = (0, _reactIntl.defineMessages)({
  confirmCloseTitle: {
    "id": "I3F5WA==",
    "defaultMessage": 'Close without saving changes?'
  },
  confirmCloseDescription: {
    "id": "qMB8GQ==",
    "defaultMessage": 'You have made some changes, closing without saving will loose the changes you make'
  },
  confirmCloseButtonConfirm: {
    "id": "yIQFKA==",
    "defaultMessage": 'Discard changes'
  },
  confirmCloseButtonCancel: {
    "id": "FF0Vyg==",
    "defaultMessage": 'Cancel'
  },
  confirmDeleteTitle: {
    "id": "ZjTMNg==",
    "defaultMessage": 'Delete observation?'
  },
  confirmDeleteButtonConfirm: {
    "id": "xxS3fw==",
    "defaultMessage": 'Yes, delete'
  },
  confirmDeleteButtonCancel: {
    "id": "qdS9PA==",
    "defaultMessage": 'Cancel'
  },
  // Header for section that includes the additional details for an observation
  detailsHeader: {
    "id": "uHtAUQ==",
    "defaultMessage": 'Details'
  },
  // Header for section with additional fields that are not defined in the preset
  additionalHeader: {
    "id": "7EPUxA==",
    "defaultMessage": 'Additional data'
  },
  // Cancel button once observation has been edited
  cancelEditButton: {
    "id": "bjpM6A==",
    "defaultMessage": 'Cancel'
  },
  // Save edit button
  saveEditButton: {
    "id": "3StVcg==",
    "defaultMessage": 'Save'
  },
  // Menu item to delete an observation
  deleteObservationMenuItem: {
    "id": "o+27Wg==",
    "defaultMessage": 'Delete observation'
  }
});
/*:: type ImageMediaItem = {
  src: string,
  type: 'image'
}*/

/*:: type Props = {
  open?: boolean,
  onRequestClose: () => void,
  onDelete: (id: string) => void,
  observation: Observation,
  // The initial image to show in the media carousel
  initialImageIndex?: number,
  onSave: (observation: Observation) => void,
  getPreset?: Observation => PresetWithAdditionalFields | void,
  /**
   * For a given attachment, return `src` and `type`
   *-/
  getMedia: GetMedia
}*/

var localeMap = {
  en: _enUS.default,
  fr: _fr.default,
  pt: _ptBR.default,
  es: _es.default
};

function getLocaleData(locale) {
  if (!locale) return localeMap.en;
  return localeMap[locale] || localeMap[locale.split('-')[0]] || localeMap.en;
}

function defaultGetMedia(_ref) {
  var type = _ref.type,
      id = _ref.id;
  if (type && type.split('/')[0] !== 'image') return;
  return {
    type: 'image',
    src: id
  };
}

var ConfirmCloseDialog = function ConfirmCloseDialog(_ref2) {
  var open = _ref2.open,
      onCancel = _ref2.onCancel,
      onConfirm = _ref2.onConfirm;
  return /*#__PURE__*/_react.default.createElement(_Dialog.default, {
    disableBackdropClick: true,
    open: open,
    onClose: onCancel,
    "aria-labelledby": "close-dialog-title",
    "aria-describedby": "close-dialog-description"
  }, /*#__PURE__*/_react.default.createElement(_DialogTitle.default, {
    id: "close-dialog-title"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, m.confirmCloseTitle)), /*#__PURE__*/_react.default.createElement(_DialogContent.default, null, /*#__PURE__*/_react.default.createElement(_DialogContentText.default, {
    id: "close-dialog-description"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, m.confirmCloseDescription))), /*#__PURE__*/_react.default.createElement(_DialogActions.default, null, /*#__PURE__*/_react.default.createElement(_Button.default, {
    onClick: onCancel,
    color: "primary"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, m.confirmCloseButtonCancel)), /*#__PURE__*/_react.default.createElement(_Button.default, {
    onClick: onConfirm,
    color: "primary",
    autoFocus: true
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, m.confirmCloseButtonConfirm))));
};

var ConfirmDeleteDialog = function ConfirmDeleteDialog(_ref3) {
  var open = _ref3.open,
      onCancel = _ref3.onCancel,
      onConfirm = _ref3.onConfirm;
  return /*#__PURE__*/_react.default.createElement(_Dialog.default, {
    disableBackdropClick: true,
    open: open,
    onClose: onCancel,
    "aria-labelledby": "delete-dialog-title"
  }, /*#__PURE__*/_react.default.createElement(_DialogTitle.default, {
    id: "delete-dialog-title"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, m.confirmDeleteTitle)), /*#__PURE__*/_react.default.createElement(_DialogActions.default, null, /*#__PURE__*/_react.default.createElement(_Button.default, {
    onClick: onCancel,
    color: "primary"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, m.confirmDeleteButtonCancel)), /*#__PURE__*/_react.default.createElement(_Button.default, {
    onClick: onConfirm,
    color: "primary",
    autoFocus: true
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, m.confirmDeleteButtonConfirm))));
};

var Accordion = (0, _styles.withStyles)({
  root: {
    border: '1px solid rgba(0, 0, 0, .125)',
    boxShadow: 'none',
    '&:before': {
      display: 'none'
    },
    '&$expanded': {
      margin: 'auto'
    }
  },
  expanded: {}
})(_Accordion.default);
var AccordionSummary = (0, _styles.withStyles)({
  root: {
    '&$expanded': {
      minHeight: 48
    }
  },
  content: {
    '&$expanded': {
      margin: '12px 0'
    }
  },
  expanded: {}
})(_AccordionSummary.default);
var AccordionDetails = (0, _styles.withStyles)({
  root: {
    display: 'flex',
    flexDirection: 'column',
    flexWrap: 'wrap',
    padding: '0 21px 10px 21px',
    '& > div:first-child': {
      marginTop: 10
    }
  }
})(_AccordionDetails.default);

var ObservationActions = function ObservationActions(_ref4) {
  var onDeleteClick = _ref4.onDeleteClick;

  var _React$useState = _react.default.useState(null),
      _React$useState2 = (0, _slicedToArray2.default)(_React$useState, 2),
      anchorEl = _React$useState2[0],
      setAnchorEl = _React$useState2[1];

  var _useState = (0, _react.useState)(null),
      _useState2 = (0, _slicedToArray2.default)(_useState, 2),
      confirm = _useState2[0],
      setConfirm = _useState2[1];

  var handleOpenClick = function handleOpenClick(event) {
    setAnchorEl(event.currentTarget);
  };

  var handleClose = function handleClose() {
    setAnchorEl(null);
  };

  var createHandleItemClick = function createHandleItemClick() {
    var action
    /*: () => any*/
    = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {};
    return function () {
      // Can't setState to a function
      setConfirm(function (state) {
        return function (didConfirm) {
          setConfirm(null);
          if (didConfirm) action();
          handleClose();
        };
      });
    };
  };

  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_IconButton.default, {
    "aria-controls": "simple-menu",
    "aria-haspopup": "true",
    onClick: handleOpenClick
  }, /*#__PURE__*/_react.default.createElement(_MoreVert.default, null)), /*#__PURE__*/_react.default.createElement(_Menu.default, {
    id: "simple-menu",
    anchorEl: anchorEl,
    keepMounted: true,
    open: Boolean(anchorEl),
    onClose: handleClose
  }, /*#__PURE__*/_react.default.createElement(_MenuItem.default, {
    onClick: createHandleItemClick(onDeleteClick)
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, m.deleteObservationMenuItem))), /*#__PURE__*/_react.default.createElement(ConfirmDeleteDialog, {
    open: !!confirm,
    onConfirm: function onConfirm() {
      return confirm && confirm(true);
    },
    onCancel: function onCancel() {
      return confirm && confirm(false);
    }
  }));
};

var DialogContent = function DialogContent(_ref5) {
  var _context, _context2, _context3;

  var _ref5$open = _ref5.open,
      open = _ref5$open === void 0 ? false : _ref5$open,
      onRequestClose = _ref5.onRequestClose,
      onSave = _ref5.onSave,
      onDelete = _ref5.onDelete,
      observation = _ref5.observation,
      initialImageIndex = _ref5.initialImageIndex,
      _ref5$getPreset = _ref5.getPreset,
      getPreset = _ref5$getPreset === void 0 ? _helpers.defaultGetPreset : _ref5$getPreset,
      _ref5$getMedia = _ref5.getMedia,
      getMedia = _ref5$getMedia === void 0 ? defaultGetMedia : _ref5$getMedia;
  var cx = useStyles();

  var _useState3 = (0, _react.useState)(observation.tags ? (0, _cloneDeep.default)(observation.tags) : {}),
      _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
      values = _useState4[0],
      setValues = _useState4[1];

  var _useState5 = (0, _react.useState)(false),
      _useState6 = (0, _slicedToArray2.default)(_useState5, 2),
      dirty = _useState6[0],
      setDirty = _useState6[1];

  var _useIntl = (0, _reactIntl.useIntl)(),
      locale = _useIntl.locale;

  var handleSave = function handleSave() {
    onSave((0, _get_set.set)(observation, 'tags', values));
    onRequestClose(false);
  };

  var handleRequestClose = function handleRequestClose() {
    // Ask for confirmation if form is dirty
    onRequestClose(dirty);
  };

  var handleDeleteClick = function handleDeleteClick() {
    onRequestClose(false);
    onDelete(observation.id);
  };

  var handleChange = function handleChange(key
  /*: Key*/
  , newValue
  /*: any*/
  ) {
    setDirty(true);
    setValues((0, _get_set.set)(values, key, newValue));
  };

  var preset = getPreset(observation) || {};
  var coords = observation.lat != null && observation.lon != null ? {
    latitude: observation.lat,
    longitude: observation.lon
  } : undefined;
  var descriptionKey = values.note ? 'note' : 'notes';
  var mediaItems
  /*: ImageMediaItem[]*/
  = (0, _reduce.default)(_context = observation.attachments || []).call(_context, function (acc, cur) {
    var item = getMedia(cur, {
      width: 800,
      height: 600
    }); // $FlowFixMe - need to fix type refinement here

    if (item && item.type === 'image') acc.push(item);
    return acc;
  }, []);
  return /*#__PURE__*/_react.default.createElement(_pickers.MuiPickersUtilsProvider, {
    utils: _dateFns.default,
    locale: getLocaleData(locale)
  }, /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_IconButton.default, {
    className: cx.closeButton,
    color: "inherit",
    onClick: handleRequestClose,
    "aria-label": "Close"
  }, /*#__PURE__*/_react.default.createElement(_Close.default, null)), mediaItems.length > 0 && /*#__PURE__*/_react.default.createElement("div", {
    className: cx.mediaWrapper
  }, /*#__PURE__*/_react.default.createElement(_MediaCarousel.default, {
    items: mediaItems,
    initialIndex: initialImageIndex,
    className: cx.media
  })), /*#__PURE__*/_react.default.createElement(_FeatureHeader.default, {
    icon: preset.icon,
    name: preset.name,
    coords: coords,
    createdAt: new Date(observation.created_at),
    action: /*#__PURE__*/_react.default.createElement(ObservationActions, {
      onDeleteClick: handleDeleteClick
    })
  }), /*#__PURE__*/_react.default.createElement(_TextField.default, {
    value: values[descriptionKey],
    onChange: function onChange(newValue) {
      return handleChange(descriptionKey, newValue);
    },
    multiline: true,
    margin: "dense",
    label: "Description",
    className: cx.descriptionField
  }), preset.fields.length > 0 && /*#__PURE__*/_react.default.createElement(Accordion, {
    TransitionProps: {
      unmountOnExit: true
    }
  }, /*#__PURE__*/_react.default.createElement(AccordionSummary, {
    expandIcon: /*#__PURE__*/_react.default.createElement(_ExpandMore.default, null),
    "aria-controls": "panel1a-content",
    id: "panel1a-header"
  }, /*#__PURE__*/_react.default.createElement(_core.Typography, {
    component: "h2",
    className: cx.sectionHeading
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, m.detailsHeader))), /*#__PURE__*/_react.default.createElement(AccordionDetails, null, (0, _map.default)(_context2 = preset.fields).call(_context2, function (field) {
    return /*#__PURE__*/_react.default.createElement(_Field.default, {
      key: field.id,
      field: field,
      value: (0, _get_set.get)(values, field.key),
      onChange: handleChange
    });
  }))), (0, _isArray.default)(preset.additionalFields) && preset.additionalFields.length > 0 && /*#__PURE__*/_react.default.createElement(Accordion, null, /*#__PURE__*/_react.default.createElement(AccordionSummary, {
    expandIcon: /*#__PURE__*/_react.default.createElement(_ExpandMore.default, null),
    "aria-controls": "panel1a-content",
    id: "panel1a-header"
  }, /*#__PURE__*/_react.default.createElement(_core.Typography, {
    component: "h2",
    className: cx.sectionHeading
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, m.additionalHeader))), /*#__PURE__*/_react.default.createElement(AccordionDetails, null, (0, _map.default)(_context3 = preset.additionalFields).call(_context3, function (field) {
    return /*#__PURE__*/_react.default.createElement(_Field.default, {
      key: field.id,
      field: field,
      value: (0, _get_set.get)(values, field.key),
      onChange: handleChange
    });
  }))), /*#__PURE__*/_react.default.createElement(_Fade.default, {
    in: dirty
  }, /*#__PURE__*/_react.default.createElement(_Collapse.default, {
    in: dirty,
    className: cx.actions
  }, /*#__PURE__*/_react.default.createElement(_Button.default, {
    color: "default",
    variant: "contained",
    className: cx.button,
    onClick: handleRequestClose
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, m.cancelEditButton)), /*#__PURE__*/_react.default.createElement(_Button.default, {
    color: "primary",
    variant: "contained",
    className: cx.button,
    onClick: handleSave
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, m.saveEditButton))))));
};

var ObservationDialog = function ObservationDialog(_ref6) {
  var open = _ref6.open,
      onRequestClose = _ref6.onRequestClose,
      otherProps = (0, _objectWithoutProperties2.default)(_ref6, ["open", "onRequestClose"]);

  var _useState7 = (0, _react.useState)(null),
      _useState8 = (0, _slicedToArray2.default)(_useState7, 2),
      confirm = _useState8[0],
      setConfirm = _useState8[1];

  var handleRequestClose = function handleRequestClose(shouldConfirm) {
    if (!shouldConfirm) {
      setConfirm(null);
      onRequestClose();
      return;
    }

    setConfirm(function (state) {
      return function (didConfirm) {
        setConfirm(null);
        if (didConfirm) onRequestClose();
      };
    });
  };

  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_Dialog.default, {
    disableBackdropClick: true,
    open: open,
    onClose: handleRequestClose,
    scroll: "body",
    fullWidth: true,
    maxWidth: "sm"
  }, open && /*#__PURE__*/_react.default.createElement(DialogContent, (0, _extends2.default)({}, otherProps, {
    onRequestClose: handleRequestClose
  }))), /*#__PURE__*/_react.default.createElement(ConfirmCloseDialog, {
    open: !!confirm,
    onConfirm: function onConfirm() {
      return confirm && confirm(true);
    },
    onCancel: function onCancel() {
      return confirm && confirm(false);
    }
  }));
};

var _default = ObservationDialog;
exports.default = _default;
var useStyles = (0, _styles.makeStyles)(function (theme) {
  return {
    closeButton: {
      position: 'absolute',
      zIndex: 999,
      left: 0,
      top: 0,
      color: 'white',
      backgroundColor: 'rgba(0,0,0,0.4)',
      borderRadius: '0 0 4px 0',
      '&:hover': {
        backgroundColor: 'rgba(0,0,0,0.5)'
      }
    },
    descriptionField: {
      boxSizing: 'border-box',
      margin: '0 10px 13.5px 10px',
      width: 'calc(100% - 20px)',
      '& .MuiInputBase-inputMultiline': theme.typography.body1,
      '& .MuiInputLabel-root': {
        opacity: 0,
        transition: 'opacity 200ms cubic-bezier(0.0, 0, 0.2, 1)'
      },
      '&:hover .MuiInputLabel-root, & .MuiInputLabel-root.Mui-focused': {
        opacity: 1
      },
      '& .MuiOutlinedInput-notchedOutline': {
        borderColor: 'rgba(0,0,0,0)'
      }
    },
    sectionHeading: {
      fontWeight: 500
    },
    mediaWrapper: {
      width: '100%',
      paddingTop: '75%',
      position: 'relative',
      height: 0
    },
    media: {
      position: 'absolute',
      top: 0,
      left: 0,
      width: '100%',
      height: '100%'
    },
    details: {
      flexDirection: 'column',
      flex: 1,
      minWidth: 320,
      flexBasis: '33%',
      backgroundColor: 'white',
      overflowY: 'scroll'
    },
    actions: {
      margin: '0 10px',
      textAlign: 'right'
    },
    button: {
      marginLeft: theme.spacing(1),
      marginTop: 14,
      marginBottom: 14
    }
  };
});
//# sourceMappingURL=ObservationDialog.js.map