import { FC, createContext, useRef, useState } from 'react';
import { HandleUploadingFileNumType } from './types';

export const DageUploadContext = createContext<{
  /**
   * 是否上传中
   */
  uploading: boolean;
  handleUploadingFileNum: (type: HandleUploadingFileNumType) => void;
} | null>(null);

export const DageUploadConsumer = DageUploadContext.Consumer;

export const DageUploadProvider: FC<{
  children: React.ReactNode;
}> = (props) => {
  /** 待上传文件数量 */
  const uploadingFileNum = useRef(0);
  const [uploading, setUploading] = useState(false);

  const handleUploadingFileNum = (type: HandleUploadingFileNumType) => {
    if (type === 'add') {
      uploadingFileNum.current += 1;
      setUploading(true);
    } else {
      uploadingFileNum.current -= 1;

      if (uploading && !uploadingFileNum.current) {
        setUploading(false);
      }
    }
  };

  return (
    <DageUploadContext.Provider value={{ uploading, handleUploadingFileNum }}>
      {props.children}
    </DageUploadContext.Provider>
  );
};
