import {useFetchWrapped} from '~/composables/useFetchWrapped';

const putOSS = (file: File, signed_url: string) => new Promise<void>((resolve, reject) => {
  let xhr = new XMLHttpRequest()
  xhr.open('PUT', signed_url as string)
  xhr.setRequestHeader('Content-Type', '')
  xhr.onload = () => {
    if (xhr.status === 200) {
      resolve()
    } else {
      reject()
    }
  }
  xhr.onerror = reject
  xhr.send(file)
})

export const useFileGo = (file: File) => new Promise<string>((resolve, reject) => {
  useFetchWrapped<req.file.Upload & AuthedRequest, string>('App.Tools_Upload.GoOss', {
    token: useLoginState().token!,
    user_id: useLoginState().user.id,
    file_name: file.name,
    file_type: file.type,
    file_size: file.size,
  }).then(async res => {
    if (res !== '') {
      try {
        await putOSS(file, res)
        let url = res.split('?')[0]
        resolve(url)
      } catch (err) {
        reject(err)
      }
    }
  }).catch(err => {
    reject(err)
  })
})