package com.lukouguoji.module_base.http.net.body

import com.lukouguoji.module_base.ktx.loge
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*

class ProgressResponseBody(
    private val url: String,
    private val body: ResponseBody,
    private val progressCallback: (url: String, total: Long, current: Long, progress: Int) -> Unit
) : ResponseBody() {

    private val bufferedSource: BufferedSource by lazy {
        buildSource(body.source()).buffer()
    }

    override fun contentLength(): Long {
        return body.contentLength()
    }

    override fun contentType(): MediaType? {
        loge("这里监听 mediaType  ${body.contentType()}")
        return body.contentType()
    }

    override fun source(): BufferedSource {
        return bufferedSource
    }

    private fun buildSource(source: Source): Source {
        return object : ForwardingSource(source) {
            var totalBytesRead = 0L
            var progress = 0

            override fun read(sink: Buffer, byteCount: Long): Long {
                val read = super.read(sink, byteCount)
                totalBytesRead += if (read != -1L) read else 0L
                val contentLength = contentLength()
                val p = (totalBytesRead * 100 / contentLength).toInt()
                //当前进度大于之前进度,才通知
                if (p > progress) {
                    progress = p
                    progressCallback(url, contentLength, totalBytesRead, p)
                }
                return read
            }
        }
    }

}