import { Upload, Button } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { useState } from 'react'
import { upload } from  './factory'
import { ErrorFetch } from './ErrorFetch'

export const UploadForm = ({url, accept, style, formData, onUploadStart, onUploadSuccess, onUploadComplete, onUploadError}) => {  
  const [fileList, setfileList] = useState([])

  const handleFileSend = async () => {
    if(onUploadStart)
      onUploadStart()
    try {
      const formDataLocal = new FormData()
      fileList.forEach((val) => {
        formDataLocal.append("files", val.originFileObj)
      })

      if(formData)
        for(var propName in formData)
          formDataLocal.append(propName, formData[propName])
      
      const response = await upload(url, formDataLocal)
      if(!response.ok)
      {
        const errorText = await response.text()        
        const error = new ErrorFetch(response.status, errorText)
        throw error
      }
      else{
        if(onUploadSuccess)
          onUploadSuccess()
      }
    } catch(error) {
      if(onUploadError)
        onUploadError(error)
    } finally {
      setfileList([])
      if(onUploadComplete)
        onUploadComplete()
    }
  }

  const isSendButtonEnabled = fileList.length > 0
  return(
    <div style={{display: 'flex', ...style}}>
      <Upload 
        name ="file"
        fileList={fileList}
        accept={accept}
        onChange={(props) => setfileList(props.fileList)}>
        <Button icon={<UploadOutlined/>}>Загрузить файл</Button>
      </Upload>
      <Button type="primary"
        disabled={!isSendButtonEnabled}
        style={{marginLeft: '10px', display:isSendButtonEnabled?'':'none'}}
        onClick={handleFileSend}>
        Отправить
      </Button>
    </div>
  )
} 