"use strict";

exports.__esModule = true;
exports.default = void 0;

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

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

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

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

var _reactSortablejs = require("react-sortablejs");

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 _MediaChunkUploader = _interopRequireDefault(require("../../MediaChunkUploader"));

const _excluded = ["children"];

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

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 PREFIX = 'SCMediaActionVideo';
const classes = {
  preview: `${PREFIX}-preview`
};
const Root = (0, _styles.styled)(_material.Box, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(({
  theme
}) => ({
  padding: theme.spacing(),
  [`& .${classes.preview}`]: {
    backgroundColor: theme.palette.background.default,
    height: 200,
    position: 'relative'
  }
}));
const UploadButton = (0, _uploadButton.asUploadButton)( /*#__PURE__*/(0, _react.forwardRef)((props, ref) => /*#__PURE__*/_react.default.createElement(_material.Button, _extends({}, props, {
  "aria-label": "upload document",
  ref: ref,
  variant: "outlined",
  color: "inherit"
}), /*#__PURE__*/_react.default.createElement(_Icon.default, null, "picture_as_pdf"), " ", /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
  id: "ui.composer.media.document.add",
  defaultMessage: "ui.composer.media.document.add"
}))));
const SortableComponent = /*#__PURE__*/(0, _react.forwardRef)((_ref, ref) => {
  let {
    children
  } = _ref,
      props = _objectWithoutPropertiesLoose(_ref, _excluded);

  return /*#__PURE__*/_react.default.createElement(_material.ImageList, _extends({
    ref: ref,
    cols: 3
  }, props), children);
});

var _default = props => {
  //PROPS
  const {
    medias = [],
    onSuccess,
    onSort,
    onDelete
  } = props; // STATE

  const [uploading, setUploading] = (0, _react.useState)({});
  const [errors, setErrors] = (0, _react.useState)({}); // CONTEXT

  const scContext = (0, _react.useContext)(_core.SCContext); // HANDLERS

  const handleSuccess = media => {
    onSuccess(media);
  };

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

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

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


  return /*#__PURE__*/_react.default.createElement(Root, null, /*#__PURE__*/_react.default.createElement(_material.Typography, {
    gutterBottom: true,
    component: "div"
  }, /*#__PURE__*/_react.default.createElement(_reactSortablejs.ReactSortable, {
    list: [...medias, ...Object.values(uploading)],
    setList: newSort => onSort(newSort.filter(s => s.upload_id === undefined)),
    tag: SortableComponent
  }, medias.map(media => /*#__PURE__*/_react.default.createElement(_material.ImageListItem, {
    key: media.id
  }, /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.preview,
    sx: {
      backgroundImage: `url(${media.image})`
    }
  }), /*#__PURE__*/_react.default.createElement(_material.ImageListItemBar, {
    position: "top",
    actionIcon: /*#__PURE__*/_react.default.createElement(_material.IconButton, {
      onClick: onDelete(media.id),
      size: "small",
      sx: {
        color: 'rgba(255, 255, 255, 0.54)'
      }
    }, /*#__PURE__*/_react.default.createElement(_Icon.default, null, "delete"))
  }))), Object.values(uploading).map(media => /*#__PURE__*/_react.default.createElement(_material.ImageListItem, {
    key: media.id,
    className: 'ignore-elements'
  }, /*#__PURE__*/_react.default.createElement(_material.Box, {
    className: classes.preview,
    sx: {
      backgroundImage: `url(${media.image})`
    }
  }, /*#__PURE__*/_react.default.createElement(_Icon.default, {
    sx: {
      position: 'absolute',
      left: 0,
      top: 0,
      width: '100%',
      height: '100%'
    }
  }, "picture_as_pdf")), /*#__PURE__*/_react.default.createElement(_material.ImageListItemBar, {
    title: /*#__PURE__*/_react.default.createElement(_material.Typography, {
      align: "center"
    }, `${Math.round(media.completed)}%`),
    position: "top"
  }))))), /*#__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(_material.Typography, {
    align: "center",
    gutterBottom: true
  }, /*#__PURE__*/_react.default.createElement(_chunkedUploady.default, {
    destination: {
      url: `${scContext.settings.portal}${_core.Endpoints.ComposerChunkUploadMedia.url()}`,
      headers: {
        Authorization: `Bearer ${scContext.settings.session.authToken.accessToken}`
      },
      method: _core.Endpoints.ComposerChunkUploadMedia.method
    },
    chunkSize: 2142880,
    multiple: true,
    accept: "application/pdf"
  }, /*#__PURE__*/_react.default.createElement(_MediaChunkUploader.default, {
    onSuccess: handleSuccess,
    onProgress: handleProgress,
    onError: handleError
  }), /*#__PURE__*/_react.default.createElement(UploadButton, {
    inputFieldName: "document"
  }))));
};

exports.default = _default;