package com.rc.core.util

import android.content.Context
import com.rc.core.log.RcLog
import com.rc.httpcore.net.DownloadListener
import com.rc.httpcore.net.DownloadTask
import java.io.File

/**
 * info
 *
 * @author ReiChin_
 */
class ApkUpdater(
    private val appContext: Context,
    private val applicationId: String,
    private val callback: DownloadCallback? = null
) {

    fun downloadApk(downloadUrl: String) {
        val fileName = "laboratory-release.apk"
        val apkFile = File(appContext.cacheDir, fileName)
        if (apkFile.exists()) {
            apkFile.delete()
        }
        val downloadTask = DownloadTask(
            listener = object : DownloadListener {
                override fun onProgress(progress: Int) {
                    RcLog.info("download apk, progress:$progress")
                    callback?.onProgress(progress)
                }

                override fun onSuccess() {
                    callback?.onSuccess(apkFile.path)
                    ApkController.installAPK(apkFile, appContext, applicationId)
                }

                override fun onFailed(errMsg: String?) {
                    callback?.onFailed(errMsg)
                }

                override fun onPaused() {
                }

                override fun onCanceled() {
                }

            }, dlPath = appContext.cacheDir.path,
            fileName = fileName,
            headers = mapOf("Accept-Encoding" to "identity")
        )
        downloadTask.execute(downloadUrl)
    }

    interface DownloadCallback {
        fun onProgress(progress: Int)
        fun onFailed(errMsg: String?)
        fun onSuccess(apkFile: String)
    }

}