package com.adealink.weparty.oss.request

import okhttp3.MediaType
import okhttp3.RequestBody
import okio.BufferedSink
import okio.ForwardingSink
import okio.buffer
import java.io.IOException

// 1. 定义进度监听接口
fun interface UploadProgressListener {
    fun onProgress(total: Long, current: Long)
}

// 2. 创建自定义RequestBody
class ProgressRequestBody(
    private val requestBody: RequestBody,
    private val listener: UploadProgressListener? = null
) : RequestBody() {
    
    private var totalSize: Long = 0

    override fun contentType(): MediaType? = requestBody.contentType()

    @Throws(IOException::class)
    override fun contentLength(): Long {
        totalSize = requestBody.contentLength()
        return totalSize
    }

    @Throws(IOException::class)
    override fun writeTo(sink: BufferedSink) {
        if (listener == null) {
            requestBody.writeTo(sink)
            return
        }

        // 3. 使用ForwardingSink包装原Sink，用于计数
        val countingSink = object : ForwardingSink(sink) {
            private var bytesWritten = 0L

            override fun write(source: okio.Buffer, byteCount: Long) {
                super.write(source, byteCount)
                bytesWritten += byteCount
                listener.onProgress(totalSize, bytesWritten)
            }
        }

        // 修正：将countingSink包装为BufferedSink
        val bufferedSink = countingSink.buffer()
        
        // 执行真正的写入
        requestBody.writeTo(bufferedSink)
        // 必须刷新
        bufferedSink.flush()
    }
}