import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useEffect } from 'react';
import { useState } from 'react';
import Preview from './Preview';
import { icons } from './settings.js';
export var context = /*#__PURE__*/React.createContext({
  current: 0,
  setCurrent: function setCurrent() {
    return null;
  },
  previewUrls: new Map(),
  setPreviewUrls: function setPreviewUrls() {
    return null;
  },
  registerImage: function registerImage() {
    return null;
  }
});

var PreviewGroup = function PreviewGroup(props) {
  var _props$previewPrefixC = props.previewPrefixCls,
      previewPrefixCls = _props$previewPrefixC === void 0 ? 'ne-image-preview' : _props$previewPrefixC,
      children = props.children;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      isShowPreview = _useState2[0],
      setShowPreview = _useState2[1];

  var _useState3 = useState(new Map()),
      _useState4 = _slicedToArray(_useState3, 2),
      previewUrls = _useState4[0],
      setPreviewUrls = _useState4[1];

  var _useState5 = useState(0),
      _useState6 = _slicedToArray(_useState5, 2),
      current = _useState6[0],
      setCurrent = _useState6[1];

  var onPreviewClose = function onPreviewClose(e) {
    e && e.stopPropagation();
    setShowPreview(false);
  };

  var previewUrlsKeys = Array.from(previewUrls.keys());
  var currentControlledKey = previewUrlsKeys[current];
  useEffect(function () {
    currentControlledKey && setCurrent(currentControlledKey);
  }, currentControlledKey);

  var registerImage = function registerImage(currentId, src, canPreview) {
    var unRegister = function unRegister() {
      setPreviewUrls(function (oldPreviewUrls) {
        var clonePreviewUrls = new Map(oldPreviewUrls);
        var deleteResult = clonePreviewUrls.delete(currentId);
        return deleteResult ? clonePreviewUrls : oldPreviewUrls;
      });
    };

    setPreviewUrls(function (oldPreviewUrls) {
      return new Map(oldPreviewUrls).set(currentId, {
        src: src,
        canPreview: canPreview
      });
    });
    return unRegister;
  };

  return /*#__PURE__*/React.createElement(context.Provider, {
    value: {
      isPreviewGroup: true,
      current: current,
      setCurrent: setCurrent,
      previewUrls: previewUrls,
      setPreviewUrls: setPreviewUrls,
      registerImage: registerImage,
      setShowPreview: setShowPreview
    }
  }, children, /*#__PURE__*/React.createElement(Preview, {
    prefixCls: previewPrefixCls,
    visible: isShowPreview,
    icons: icons,
    onClose: onPreviewClose,
    src: previewUrls.get(current)
  }));
};

export default PreviewGroup;