package com.qimai.android.fetch.extention

import android.os.Environment
import com.qimai.android.fetch.download.ProgressListener
import okhttp3.ResponseBody
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

/**
 *   created by wangwei   ON 2019-12-31  email:wangwei_5521@163.com
 *   @version 1.1.1
 *   @Description
 **/

/**
 * 保存文件
 * note： string 文件的名字
 */
fun String.saveFile(response: ResponseBody, progressListener: ProgressListener): File {
    if (this.isEmpty()) {
        throw  IllegalArgumentException("file name cannot allow empty ")
    }
    var fileDir = "${Environment.getExternalStorageDirectory()}" +
            "${File.separator}QMDoowload${File.separator}"

    val contentLength: Long = response.contentLength()
    var inputStream: InputStream? = null
    val buf = ByteArray(1024)
    var len = 0
    var fos: FileOutputStream? = null
    return try {
        inputStream = response.byteStream()
        var sum: Long = 0
        val dir =
            File(fileDir)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        var file   =  File(dir,this)
        fos = FileOutputStream(file)
        while (inputStream.read(buf).also { len = it } != -1) {
            sum += len.toLong()
            fos.write(buf, 0, len)
            val finalSum = sum
            progressListener.onResponseProgress(
                finalSum,
                contentLength,
                (finalSum * 1.0f / contentLength * 100).toInt(),
                finalSum == contentLength,
                dir.absolutePath
            )
        }
        fos.flush()
        dir
    } finally {
        try {
            response.close()
            if (inputStream != null) inputStream.close()
        } catch (e: IOException) {
        }
        try {
            if (fos != null) fos.close()
        } catch (e: IOException) {
        }
    }

}