function amazonUpload(file, prerequest_ret, upload_request) {
   console.log("amazonUpload", file, prerequest_ret, upload_request);
   let handler = prerequest_ret.parts ? amazonUploadMultipart : amazonUploadSimple;
   return handler(file, prerequest_ret, upload_request);
}

async function amazonUploadSimple(file, prerequest_ret, upload_request) {
   console.log("amazonUploadSimple", file, prerequest_ret, upload_request);
   const xhr = await put(prerequest_ret.url, file, { 'onuploadprogress': upload_request.onuploadprogress });
   console.log("Chunk upload result:", xhr);

   if(xhr.status >= 400) {
      console.log("Upload error: ", uploadRes.status);
      return;
   }

   const res = await fetch(`/?op=finish_upload&file_size=${file.size}&file_code=${prerequest_ret.file_code}`);
   const ret = await res.json();
   console.log("finishUpload: ", ret);
   return ret;
}

async function amazonUploadMultipart(file, prerequest_ret, upload_request) {
   console.log("amazonUploadMultipart", file, prerequest_ret, upload_request);
   let uploaded_parts = {};
   let i = 1;
   let loaded = 0;
   for(const part of prerequest_ret.parts) {
      const xhr = await put(part.url, file.slice(part.offset, part.offset+part.size), {
         'onuploadprogress': evt => upload_request.onuploadprogress({ loaded: loaded + evt.loaded, total: evt.total }),
      });
      console.log("Chunk upload result:", xhr);

      if(xhr.status >= 400) {
         console.log("Upload error: ", uploadRes.status);
         return;
      }

      const etag = xhr.getResponseHeader("ETag").replaceAll('"', '');
      console.log("etag:", etag);
      uploaded_parts[`part_${i++}`] = etag;
      loaded += part.size;
   }

   console.log('uploaded_parts:', uploaded_parts);

   const ret = await post("/", {
      'op': 'finish_upload',
      'file_size': file.size,
      'file_code': prerequest_ret.file_code,
      'upload_id': prerequest_ret.upload_id,
      ...uploaded_parts,
   });

   console.log("finishUpload: ", ret);
   return ret;
}

uploadPlugins['amazon'] = amazonUpload;
