package com.yidian.common.utils

import android.util.Log
import okhttp3.*
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * 该类只是为了模拟下载文件
 */
class FileDownloadUtil private constructor(){
    companion object{
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED){ FileDownloadUtil()}
    }
    private  val TAG = "FileDownloadUtil"
    private var requestCall: Call? = null
    private val client: OkHttpClient = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS).build()
    private var cancel = false
    fun startDownload(url:String){
        cancel = false
        Log.e(TAG, "startDownload: $url" )

        if (!url.startsWith("http"))return
      val  request = Request.Builder().url(url).build()

        client.newCall(request).enqueue(object :Callback{
            override fun onFailure(call: Call, e: IOException) {
                Log.e(TAG, "onFailure: " )

            }

            override fun onResponse(call: Call, response: Response) {
               try {
                   val ins = response.body!!.byteStream()
                   val total = response.body!!.contentLength()
                   var sum = 0
                   var len =0
                   val buffer = ByteArray(2048)
                   while (!cancel){
                       len = ins.read(buffer)
                       if (len == -1) break
                       sum+=len
                       val progress = (sum.toFloat()/total)
                       Log.d("yue.huang","progress---:"+progress)
//                       if (progress>=0.3) break
                   }

               }catch (e:Exception){
                   requestCall = null
               }finally {
                   response.body?.close()
               }

            }


        })


    }
    fun stopDownload(){
        cancel = true
        requestCall?.cancel()
        requestCall=null
    }

}