package com.isidroid.network

import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okio.BufferedSink
import timber.log.Timber
import java.io.File

class ProgressEmittingRequestBody(
    private val mediaType: String,
    private val file: File,
) : RequestBody() {
    override fun contentType(): MediaType? = mediaType.toMediaTypeOrNull()
    override fun contentLength(): Long = file.length()

    override fun writeTo(sink: BufferedSink) {
        val buffer = ByteArray(1024)
        var uploaded: Long = 0
        val inputStream = file.inputStream()
        val fileSize = file.length()

        try {
            while (true) {

                val read = inputStream.read(buffer)
                if (read == -1) break

                uploaded += read
                sink.write(buffer, 0, read)

                val progress = (((uploaded / fileSize.toDouble())) * 100).toInt()
            }

        } catch (e: Exception) {
            Timber.e(e)
        } finally {
            inputStream.close()
        }
    }
}