"use strict";

exports.__esModule = true;
exports.default = ChangeCover;

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

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

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

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

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

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

var _ConfirmDialog = _interopRequireDefault(require("../../shared/ConfirmDialog/ConfirmDialog"));

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

var _CircularProgress = _interopRequireDefault(require("@mui/material/CircularProgress"));

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

const _excluded = ["onChange", "autoHide", "className"];

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 PREFIX = 'SCChangeCoverButton';
const classes = {
  root: `${PREFIX}-root`,
  helpPopover: `${PREFIX}-help-popover`,
  addMenuItem: `${PREFIX}-add-menuItem`,
  delMenuItem: `${PREFIX}-del-menuItem`
};
const Root = (0, _styles.styled)(_material.Box, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  display: 'flex',
  alignItems: 'center',
  flexWrap: 'wrap'
}));

/**
 *> API documentation for the Community-UI Change Cover component. Learn about the available props and the CSS API.
 *
 #### Import
 ```jsx
 import {ChangeCover} from '@selfcommunity/ui';
 ```

 #### Component Name
 The name `SCChangeCoverButton` can be used when providing style overrides in the theme.

 #### CSS

 |Rule Name|Global class|Description|
 |---|---|---|
 |root|.SCChangeCoverButton-root|Styles applied to the root element.|
 |helpPopover|.SCChangeCoverButton-help-popover|Styles applied to the help popover element.|
 |addMenuItem|.SCChangeCoverButton-add-menuItem|Styles applied to the add menu element.|
 |delMenuItem|.SCChangeCoverButton-del-menuItem|Styles applied to the del menu element.|

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

  const {
    onChange,
    autoHide,
    className
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); //CONTEXT


  const scUserContext = (0, _react.useContext)(_core.SCUserContext); //STATE

  let fileInput = (0, _react.useRef)(null);

  const [anchorEl, setAnchorEl] = _react.default.useState(null);

  const open = Boolean(anchorEl);

  const [anchorElPopover, setAnchorElPopover] = _react.default.useState(null);

  const [openDeleteCoverDialog, setOpenDeleteCoverDialog] = (0, _react.useState)(false);
  const [isDeletingCover, setIsDeletingCover] = (0, _react.useState)(false);
  const [loading, setLoading] = (0, _react.useState)(false); // HANDLERS

  const handleClick = event => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const hasCover = scUserContext.user && scUserContext.user.cover !== null;

  const handleClickHelpButton = event => {
    setAnchorElPopover(event.currentTarget);
  };

  const handleCloseHelpPopover = () => {
    setAnchorElPopover(null);
  };

  const isOpen = Boolean(anchorElPopover); // Anonymous

  if (!scUserContext.user) {
    return null;
  }
  /**
   * Handles file upload
   * @param event
   */


  function handleUpload(event) {
    fileInput = event.target.files[0];
    handleSave();
  }
  /**
   * Handles deletion of a specific cover
   * @param id
   */


  function deleteCover() {
    setIsDeletingCover(true);
    handleSave(true);
  }
  /**
   * Handles cover saving after upload and delete actions
   */


  function handleSave(performDelete = false) {
    setLoading(true);
    const formData = new FormData();

    if (!performDelete) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      // @ts-ignore
      formData.append('cover', fileInput);
    } else {
      formData.append('cover', '');
    }

    _core.http.request({
      url: _core.Endpoints.UpdateUser.url({
        id: scUserContext.user['id']
      }),
      method: _core.Endpoints.UpdateUser.method,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: formData
    }).then(res => {
      scUserContext.updateUser({
        cover: res.data.cover
      });
      onChange && onChange(res.data.cover);
      setAnchorEl(null);
      setLoading(false);

      if (performDelete) {
        setIsDeletingCover(false);
        setOpenDeleteCoverDialog(false);
      }
    }).catch(error => {
      setLoading(false);
      console.log(error);
    });
  }
  /**
   * Renders change cover card
   */


  const cc = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_material.Button, _extends({
    size: "small",
    variant: "contained",
    disabled: loading,
    onClick: handleClick
  }, rest), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.changeCover.button.change",
    defaultMessage: "ui.changeCover.button.change"
  })), /*#__PURE__*/_react.default.createElement(_material.Menu, {
    anchorEl: anchorEl,
    open: open,
    onClose: handleClose
  }, loading ? /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
    sx: {
      justifyContent: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_CircularProgress.default, {
    size: 15
  })) : /*#__PURE__*/_react.default.createElement(_material.Box, null, /*#__PURE__*/_react.default.createElement("input", {
    type: "file",
    onChange: () => handleUpload(event),
    ref: fileInput,
    hidden: true
  }), /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
    disabled: loading,
    onClick: () => fileInput.current.click(),
    className: classes.addMenuItem
  }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, null, /*#__PURE__*/_react.default.createElement(_Icon.default, {
    fontSize: "small"
  }, "add_circle_outline")), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.changeCover.button.upload",
    defaultMessage: "ui.changeCover.button.upload"
  })), hasCover && /*#__PURE__*/_react.default.createElement(_material.MenuItem, {
    className: classes.delMenuItem,
    onClick: () => setOpenDeleteCoverDialog(true)
  }, /*#__PURE__*/_react.default.createElement(_material.ListItemIcon, null, /*#__PURE__*/_react.default.createElement(_Icon.default, {
    fontSize: "small"
  }, "delete")), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.changeCover.button.delete",
    defaultMessage: "ui.changeCover.button.delete"
  })))), /*#__PURE__*/_react.default.createElement(_material.IconButton, {
    className: classes.helpPopover,
    color: "primary",
    "aria-label": "upload picture",
    component: "span",
    onClick: handleClickHelpButton
  }, /*#__PURE__*/_react.default.createElement(_Icon.default, {
    fontSize: "small"
  }, "help_outline")), isOpen && /*#__PURE__*/_react.default.createElement(_material.Popover, {
    open: isOpen,
    anchorEl: anchorElPopover,
    onClose: handleCloseHelpPopover,
    anchorOrigin: {
      vertical: 'bottom',
      horizontal: 'right'
    }
  }, /*#__PURE__*/_react.default.createElement(_material.Box, {
    sx: {
      p: '10px'
    }
  }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    component: "h3"
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.changeCover.button.uploadA",
    defaultMessage: "ui.changeCover.button.uploadA"
  })), /*#__PURE__*/_react.default.createElement(_material.Divider, null), /*#__PURE__*/_react.default.createElement(_material.Typography, {
    component: "span"
  }, /*#__PURE__*/_react.default.createElement("ul", {
    className: "list"
  }, /*#__PURE__*/_react.default.createElement("li", null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.changeCover.listF",
    defaultMessage: "ui.changeCover.listF"
  })), /*#__PURE__*/_react.default.createElement("li", null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.changeCover.listD",
    defaultMessage: "ui.changeCover.listF"
  })), /*#__PURE__*/_react.default.createElement("li", null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.changeCover.listW",
    defaultMessage: "ui.changeCover.listF"
  })))))), openDeleteCoverDialog && /*#__PURE__*/_react.default.createElement(_ConfirmDialog.default, {
    open: openDeleteCoverDialog,
    title: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.changeCover.dialog.msg",
      defaultMessage: "ui.changeCover.dialog.msg"
    }),
    onConfirm: deleteCover,
    isUpdating: isDeletingCover,
    onClose: () => {
      setOpenDeleteCoverDialog(false);
      setAnchorEl(null);
    }
  }));
  /**
   * Renders root object (if not hidden by autoHide prop)
   */


  if (!autoHide) {
    return /*#__PURE__*/_react.default.createElement(Root, _extends({}, rest, {
      className: (0, _classnames.default)(classes.root, className)
    }), cc);
  }

  return null;
}