"use strict";

exports.__esModule = true;
exports.default = MessageMediaUploader;

var _uploadButton = require("@rpldy/upload-button");

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

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

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

var _chunkedUploady = _interopRequireDefault(require("@rpldy/chunked-uploady"));

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

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

var _Widget = _interopRequireDefault(require("../../Widget"));

var _MessageChunkUploader = _interopRequireDefault(require("../../../shared/MessageChunkUploader"));

var _uploadPreview = _interopRequireDefault(require("@rpldy/upload-preview"));

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

const UploadButton = (0, _uploadButton.asUploadButton)( /*#__PURE__*/(0, _react.forwardRef)((props, ref) => /*#__PURE__*/_react.default.createElement(_material.IconButton, _extends({}, props, {
  ref: ref
}), /*#__PURE__*/_react.default.createElement(_Icon.default, null, "upload"))));
const PREFIX = 'SCMessageMediaUploader';
const classes = {
  previewContainer: `${PREFIX}-preview-container`,
  mediaUploadSection: `${PREFIX}-media-upload-section`,
  uploadButton: `${PREFIX}-upload-button`,
  docPreview: `${PREFIX}-doc-preview`,
  docLoadingPreview: `${PREFIX}-doc-loading-preview`,
  progress: `${PREFIX}-progress`,
  clearMedia: `${PREFIX}-clear-media`
};
const Root = (0, _styles.styled)(_material.Box, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  [`& .${classes.previewContainer}`]: {
    display: 'flex',
    justifyContent: 'center',
    img: {
      maxWidth: '50%'
    },
    video: {
      maxWidth: '40%'
    }
  },
  [`& .${classes.mediaUploadSection}`]: {
    backgroundColor: theme.palette.grey['A200']
  },
  [`& .${classes.uploadButton}`]: {
    backgroundColor: theme.palette.common.white
  },
  [`& .${classes.docPreview}`]: {
    height: 200,
    width: 400,
    position: 'relative'
  },
  [`& .${classes.docLoadingPreview}`]: {
    backgroundColor: theme.palette.background.default,
    height: 100,
    width: 200,
    position: 'relative',
    '& .MuiCircularProgress-root': {
      position: 'absolute',
      top: '40%',
      left: '45%'
    },
    [`& .${classes.progress}`]: {
      display: 'flex',
      justifyContent: 'center'
    },
    [`& .${classes.clearMedia}`]: {
      display: 'flex',
      justifyContent: 'flex-end'
    }
  }
}));

function MessageMediaUploader(props) {
  //PROPS
  const {
    forwardMessageFile,
    onClose,
    onFileUploaded,
    onFileCleared
  } = props; // STATE

  const [file, setFile] = (0, _react.useState)(null);
  const [fileType, setFileType] = (0, _react.useState)(null);
  const [uploading, setUploading] = (0, _react.useState)({});
  const previewMethodsRef = (0, _react.useRef)();
  const [previews, setPreviews] = (0, _react.useState)([]);
  const [loaded, setLoaded] = (0, _react.useState)(false);
  const [loading, setLoading] = (0, _react.useState)(false);
  const [errors, setErrors] = (0, _react.useState)({}); // CONTEXT

  const scContext = (0, _react.useContext)(_core.SCContext); // Chunk Upload handlers

  const onPreviewsChanged = (0, _react.useCallback)(previews => {
    setPreviews(previews);
  }, []);
  const onClear = (0, _react.useCallback)(() => {
    var _previewMethodsRef$cu;

    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignore
    if ((_previewMethodsRef$cu = previewMethodsRef.current) != null && _previewMethodsRef$cu.clear) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      // @ts-ignore
      previewMethodsRef.current.clear();
    }

    setPreviews([]);
    setFile(null);
    setFileType(null);
    forwardMessageFile(null);
    setLoaded(false);
    onFileCleared();
  }, [previewMethodsRef]);

  const handleSuccess = media => {
    setLoaded(true);
    setLoading(false);
    setFile(media);
    forwardMessageFile(media.file_uuid);
    onFileUploaded();
  };

  const handleProgress = chunks => {
    setLoading(true);
    setUploading(Object.assign({}, chunks));
  };

  const handleStart = type => {
    setFileType(type);
  };

  const handleError = (chunk, error) => {
    setErrors(Object.assign({}, errors, {
      [chunk.id]: Object.assign({}, chunk, {
        error
      })
    }));
    onClear();
  };

  const handleRemoveErrors = id => {
    return () => {
      delete errors[id];
      setErrors(Object.assign({}, errors));
      setFile(null);
      setLoading(false);
    };
  };
  /**
   * Renders root object
   */


  return /*#__PURE__*/_react.default.createElement(Root, null, /*#__PURE__*/_react.default.createElement(_Widget.default, {
    className: classes.mediaUploadSection
  }, /*#__PURE__*/_react.default.createElement(_material.CardHeader, {
    action: /*#__PURE__*/_react.default.createElement(_Icon.default, {
      onClick: onClose
    }, "close")
  }), /*#__PURE__*/_react.default.createElement(_material.CardContent, null, /*#__PURE__*/_react.default.createElement(_material.Box, null, Object.keys(errors).map(id => /*#__PURE__*/_react.default.createElement(_material.Fade, {
    in: true,
    key: id
  }, /*#__PURE__*/_react.default.createElement(_material.Alert, {
    severity: "error",
    onClose: handleRemoveErrors(id)
  }, /*#__PURE__*/_react.default.createElement(_material.AlertTitle, null, errors[id].name), errors[id].error)))), /*#__PURE__*/_react.default.createElement(_chunkedUploady.default, {
    destination: {
      url: `${scContext.settings.portal}${_core.Endpoints.PrivateMessageUploadMediaInChunks.url()}`,
      headers: {
        Authorization: `Bearer ${scContext.settings.session.authToken.accessToken}`
      },
      method: _core.Endpoints.PrivateMessageUploadMediaInChunks.method
    },
    chunkSize: 2142880,
    chunked: true
  }, /*#__PURE__*/_react.default.createElement(_MessageChunkUploader.default, {
    onStart: handleStart,
    onSuccess: handleSuccess,
    onProgress: handleProgress,
    onError: handleError
  }), /*#__PURE__*/_react.default.createElement(_material.Box, {
    display: "grid"
  }, /*#__PURE__*/_react.default.createElement(_material.Box, {
    gridColumn: "span 12",
    className: classes.progress
  }, Object.values(uploading).map((chunk, index) => /*#__PURE__*/_react.default.createElement("div", {
    key: index
  }, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    align: "center"
  }, `${Math.round(chunk.completed)}%`)))), /*#__PURE__*/_react.default.createElement(_material.Box, {
    gridColumn: "span 12",
    sx: {
      display: 'flex',
      justifyContent: 'center'
    }
  }, !file && !loading && /*#__PURE__*/_react.default.createElement(UploadButton, {
    className: classes.uploadButton,
    inputFieldName: "qqfile"
  })), /*#__PURE__*/_react.default.createElement(_material.Box, {
    gridColumn: "span 12",
    className: classes.clearMedia
  }, previews.length && loaded ? /*#__PURE__*/_react.default.createElement(_material.IconButton, {
    onClick: onClear
  }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "close")) : null)), /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.previewContainer
  }, fileType && fileType.startsWith(_core.SCMessageFileType.DOCUMENT) ? /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: loaded ? classes.docPreview : classes.docLoadingPreview
  }, file && loaded ? /*#__PURE__*/_react.default.createElement("iframe", {
    src: file.file_url,
    title: "file",
    width: "100%",
    height: "100%",
    style: {
      resize: 'both'
    },
    loading: "lazy"
  }) : /*#__PURE__*/_react.default.createElement(_material.CircularProgress, {
    size: 30
  })) : /*#__PURE__*/_react.default.createElement(_uploadPreview.default, {
    rememberPreviousBatches: true,
    previewMethodsRef: previewMethodsRef,
    onPreviewsChanged: onPreviewsChanged
  }))))));
}