package com.cheng.blzb.common

import android.app.Activity
import android.graphics.Color
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.azhon.appupdate.manager.DownloadManager
import com.cheng.blzb.BuildConfig
import com.cheng.blzb.R
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.dialog.UpdateVersionDialog
import com.cheng.blzb.utils.UIUtils
import com.example.base.extensions.toast

object AppUpdate {

    private val apkName = "appupdate.apk"

    fun checkUpdate(fragment: Fragment, isManual: Boolean, clickFun: () -> Unit?) {

        if (isManual) {
            toast(fragment.getString(R.string.check_version_ing))
        }

        val result: com.cheng.blzb.bean.VersionEntity? = UserConfigManager.userConfig?.config?.versionEntity
        result?.apply {
            if (UIUtils.checkVersion(version, BuildConfig.VERSION_NAME)) {
                if (last_version_force == BuildConfig.VERSION_NAME) {
                    force = true
                } else if (UIUtils.checkVersion(last_version_force, BuildConfig.VERSION_NAME)) {
                    force = true
                }
                clickFun.invoke()
                com.cheng.blzb.common.AppUpdate.startUpdate(result, fragment)
            } else {
                if (isManual) {
                    toast(fragment.getString(R.string.curr_new_version))
                }
            }
        }
    }

    private fun startUpdate(versionEntity: com.cheng.blzb.bean.VersionEntity, fragment: Fragment) {
        UpdateVersionDialog.newInstance(versionEntity).show(fragment.childFragmentManager, null)
    }

    private fun startUpdateDialog(result: com.cheng.blzb.bean.VersionEntity?, activity: Activity) {
        if (result == null) return
        val manager = DownloadManager.Builder(activity).run {
            apkUrl(result.url)
            apkName(com.cheng.blzb.common.AppUpdate.apkName)
            smallIcon(R.mipmap.ic_launcher_icon)
            dialogImage(R.mipmap.ic_update_version_bg_z)
            showNewerToast(true)
            apkVersionName(result.version)
            apkSize(result.app_size)
            apkDescription(result.description)
            enableLog(true)
            jumpInstallPage(true)
            dialogButtonTextColor(Color.WHITE)
            showNotification(true)
            showBgdToast(false)
            when (result.force) {
                true -> forcedUpgrade(true)
                else -> forcedUpgrade(false)
            }
            dialogButtonColor(ContextCompat.getColor(activity, R.color.colorAccent))
            dialogProgressBarColor(ContextCompat.getColor(activity, R.color.colorAccent))
            notifyId(1011)
            build()
        }
        manager.download()
    }

}