package com.zxhl.cms.net.callback

import com.zxhl.cms.common.Constant
import com.zxhl.cms.net.model.other.FileLoadEvent
import com.zxhl.cms.utils.RxBus
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*


class DownloadResponseBody : ResponseBody {

    private val responseBody: ResponseBody
    private var bufferedSource: BufferedSource? = null

    constructor(responseBody: ResponseBody) : super() {
        this.responseBody = responseBody
    }


    override fun contentLength(): Long = responseBody.contentLength()

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

    override fun source(): BufferedSource {
        if (bufferedSource == null) {
            bufferedSource = source(responseBody.source()).buffer();
        }
        return bufferedSource as BufferedSource
    }

    private fun source(source: Source): Source {

        return object : ForwardingSource(source) {

            var totalBytesRead = 0L

            override fun read(sink: Buffer, byteCount: Long): Long {
                var bytesRead: Long = super.read(sink, byteCount)
                totalBytesRead += if (bytesRead !== -1L) bytesRead else 0
                val progress = (totalBytesRead * 100 / responseBody.contentLength())
                RxBus.get().post(Constant.UPDATE_DOWNLOAD_FILE_PROGRESS, FileLoadEvent(100, progress))
                return bytesRead
            }
        }
    }
}