"use strict";

exports.__esModule = true;
exports.default = ChangePictureDialog;

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

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

var _Button = _interopRequireDefault(require("@mui/material/Button"));

var _Typography = _interopRequireDefault(require("@mui/material/Typography"));

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

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

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

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

var _ImageList = _interopRequireDefault(require("@mui/material/ImageList"));

var _ImageListItem = _interopRequireDefault(require("@mui/material/ImageListItem"));

var _BaseDialog = _interopRequireDefault(require("../../../shared/BaseDialog"));

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 = ["open", "onChange", "onClose", "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 = 'SCChangePictureDialog';
const classes = {
  root: `${PREFIX}-root`,
  actions: `${PREFIX}-actions`,
  upload: `${PREFIX}-upload`,
  imageItem: `${PREFIX}-imageItem`
};
const Root = (0, _styles.styled)(_material.Card, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  maxWidth: 800,
  marginBottom: theme.spacing(2),
  [`& .${classes.actions}`]: {
    display: 'flex',
    justifyContent: 'flex-end'
  }
}));

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

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


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

  const [file, setFile] = (0, _react.useState)(scUserContext.user['avatar']);
  const [primary, setPrimary] = (0, _react.useState)(null);
  const [avatars, setAvatars] = (0, _react.useState)([]);
  const [deleteAvatarId, setDeleteAvatarId] = (0, _react.useState)(null);
  let fileInput = (0, _react.useRef)(null);
  const [openDeleteAvatarDialog, setOpenDeleteAvatarDialog] = (0, _react.useState)(false);
  const [isDeletingAvatar, setIsDeletingAvatar] = (0, _react.useState)(false);
  const [loading, setLoading] = (0, _react.useState)(false);
  /**
   * Handles open confirm delete avatar dialog
   * @param id
   */

  function handleOpen(id) {
    setOpenDeleteAvatarDialog(true);
    setDeleteAvatarId(id);
  }
  /**
   * Handles avatar upload
   * @param event
   */


  function handleUpload(event) {
    fileInput = event.target.files[0]; // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignore

    setFile(URL.createObjectURL(fileInput));
    handleSave();
  }
  /**
   * Performs save avatar after upload
   */


  function handleSave() {
    setLoading(true);
    const formData = new FormData(); // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignore

    formData.append('avatar', fileInput);

    _core.http.request({
      url: _core.Endpoints.AddAvatar.url({
        id: scUserContext.user['id']
      }),
      method: _core.Endpoints.AddAvatar.method,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: formData
    }).then(res => {
      setAvatars(prev => [...prev, res.data]);
      selectPrimaryAvatar(res.data);
      setLoading(false);
    }).catch(error => {
      console.log(error);
    });
  }
  /**
   * Fetches the list of scUser's avatars
   */


  function fetchUserAvatar() {
    _core.http.request({
      url: _core.Endpoints.GetAvatars.url({
        id: scUserContext.user['id']
      }),
      method: _core.Endpoints.GetAvatars.method
    }).then(res => {
      const primary = getPrimaryAvatar(res.data);

      if (res.data && res.data.results.length) {
        setAvatars(res.data.results);
        setPrimary(primary.id);
        setFile(primary.avatar);
      }
    }).catch(error => {
      console.log(error);
    });
  }
  /**
   * Gets the primary avatar from a list of avatars
   * @param data
   */


  function getPrimaryAvatar(data) {
    return data.results.find(a => a.primary === true);
  }
  /**
   * Selects primary avatar
   * Only if another avatar is selected (primary !== avatar.id)
   * @param avatar
   */


  function selectPrimaryAvatar(avatar) {
    if (avatar.id !== primary) {
      _core.http.request({
        url: _core.Endpoints.SetPrimaryAvatar.url({
          id: scUserContext.user['id']
        }),
        method: _core.Endpoints.SetPrimaryAvatar.method,
        data: {
          avatar_id: avatar.id
        }
      }).then(() => {
        scUserContext.updateUser({
          avatar: avatar.avatar
        });
        setPrimary(avatar.id);
        onChange && onChange(avatar);
      }).catch(error => {
        console.log(error);
      });
    }
  }
  /**
   * Handles deletion of a specific avatar
   * @param id
   */


  function deleteAvatar() {
    setIsDeletingAvatar(true);

    _core.http.request({
      url: _core.Endpoints.RemoveAvatar.url({
        id: scUserContext.user['id']
      }),
      method: _core.Endpoints.RemoveAvatar.method,
      data: {
        avatar_id: deleteAvatarId
      }
    }).then(() => {
      const _avatars = avatars.filter(a => a.id !== deleteAvatarId);

      setAvatars(_avatars);
      setIsDeletingAvatar(false);
      setOpenDeleteAvatarDialog(false);

      if (primary === deleteAvatarId) {
        if (_avatars.length > 0) {
          selectPrimaryAvatar(_avatars[_avatars.length - 1]);
        }
      }
    }).catch(error => {
      setOpenDeleteAvatarDialog(false);
      console.log(error);
    });
  }
  /**
   * On mount, fetches the list of scUser's avatars
   */


  (0, _react.useEffect)(() => {
    fetchUserAvatar();
  }, []);
  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    className: (0, _classnames.default)(classes.root, className)
  }, rest), openDeleteAvatarDialog && /*#__PURE__*/_react.default.createElement(_ConfirmDialog.default, {
    open: openDeleteAvatarDialog,
    title: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.changePicture.dialog.msg",
      defaultMessage: "ui.changePicture.dialog.msg"
    }),
    btnConfirm: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.changePicture.dialog.confirm",
      defaultMessage: "ui.changePicture.dialog.confirm"
    }),
    onConfirm: deleteAvatar,
    isUpdating: isDeletingAvatar,
    onClose: () => setOpenDeleteAvatarDialog(false)
  }), /*#__PURE__*/_react.default.createElement(_BaseDialog.default, {
    title: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      defaultMessage: "ui.changePicture.title",
      id: "ui.changePicture.title"
    }),
    onClose: onClose,
    open: open
  }, /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.upload
  }, /*#__PURE__*/_react.default.createElement("input", {
    type: "file",
    onChange: () => handleUpload(event),
    ref: fileInput,
    hidden: true
  }), /*#__PURE__*/_react.default.createElement(_Button.default, {
    disabled: loading,
    variant: "outlined",
    onClick: () => fileInput.current.click()
  }, loading ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_CircularProgress.default, {
    size: 15
  })) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_Icon.default, {
    fontSize: "small"
  }, "folder_open"), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.changePicture.button.upload",
    defaultMessage: "ui.changePicture.button.upload"
  }))), /*#__PURE__*/_react.default.createElement(_Typography.default, {
    sx: {
      fontSize: 10
    },
    color: "text.secondary",
    gutterBottom: true
  }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.changePicture.listF",
    defaultMessage: "ui.changePicture.listF"
  }), " ", /*#__PURE__*/_react.default.createElement("br", null), /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
    id: "ui.changePicture.listS",
    defaultMessage: "ui.changePicture.listS"
  }))), /*#__PURE__*/_react.default.createElement(_ImageList.default, {
    cols: 3,
    rowHeight: 'auto'
  }, avatars.map(avatar => /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.imageItem,
    key: avatar.id
  }, /*#__PURE__*/_react.default.createElement(_ImageListItem.default, {
    key: avatar.id,
    onClick: () => selectPrimaryAvatar(avatar),
    sx: {
      border: primary === avatar.id ? 'solid' : null
    }
  }, /*#__PURE__*/_react.default.createElement("img", {
    src: avatar.avatar,
    loading: "lazy",
    alt: 'img'
  }), /*#__PURE__*/_react.default.createElement(_material.ImageListItemBar, {
    position: "top",
    actionIcon: /*#__PURE__*/_react.default.createElement(_material.IconButton, {
      onClick: () => handleOpen(avatar.id),
      size: "small",
      sx: {
        color: 'rgba(255, 255, 255, 0.54)'
      }
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "delete"))
  })))))));
}