package com.adealink.weparty.update

import androidx.fragment.app.FragmentActivity
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.log.Log
import com.adealink.frame.util.AppUtil
import com.adealink.frame.util.PackageUtil
import com.adealink.frame.util.differentDays
import com.adealink.frame.util.runOnUiThread
import com.adealink.weparty.R
import com.adealink.weparty.commonui.widget.CommonDialog
import com.adealink.weparty.config.GlobalConfigType
import com.adealink.weparty.config.IGlobalConfigListener
import com.adealink.weparty.storage.AppPref
import com.google.android.play.core.appupdate.AppUpdateInfo
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.install.InstallStateUpdatedListener
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.InstallStatus
import com.google.android.play.core.install.model.UpdateAvailability
import java.lang.Long.max
import java.lang.ref.WeakReference
import java.util.Date
import kotlin.math.min

val updateManager: IUpdateManager by lazy { UpdateManager() }

class UpdateManager : IUpdateManager, IGlobalConfigListener {
    private val appUpdateManager by lazy { AppUpdateManagerFactory.create(AppUtil.appContext) }
    private var activityWeakReference: WeakReference<FragmentActivity>? = null
    private val forceUpdateVersionCodeSet = mutableSetOf<Int>()
    private var isConfigGet = false
    private val installStateUpdatedListener by lazy {
        InstallStateUpdatedListener { state ->
            if (state.installStatus() == InstallStatus.DOWNLOADED) {
                showCompleteUpdateDialog()
            }
        }
    }

    init {
        // TODO: 补充强制升级
//        globalConfigManager.addListener(GlobalConfigType.GLOBAL_FORCE_UPDATE, this)
//        globalConfigManager.getConfig(GlobalConfigType.GLOBAL_FORCE_UPDATE)?.let {
//            doOnConfigGet(it)
//        }
    }

    override fun checkUpdate(activity: FragmentActivity) {
        if (!isConfigGet) {
            Log.d(TAG_UPDATE, "checkUpdate, updateConfigNoReady")
            return
        }
        activityWeakReference = WeakReference(activity)
        appUpdateManager.appUpdateInfo.addOnSuccessListener { appUpdateInfo ->
            Log.i(
                TAG_UPDATE,
                "check update success, availableVersionCode:${appUpdateInfo.availableVersionCode()}"
            )
            if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {
                showCompleteUpdateDialog()
                return@addOnSuccessListener
            }
            if (appUpdateInfo.updateAvailability()
                == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS
            ) {
                startUpdate(appUpdateInfo, AppUpdateType.IMMEDIATE)
                return@addOnSuccessListener
            }
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE) {
                if (shouldUpdateImmediate()) {
                    startUpdate(appUpdateInfo, AppUpdateType.IMMEDIATE)
                    return@addOnSuccessListener
                }
                if (appUpdateInfo.updatePriority() == PRIORITY_FORE_UPDATE && appUpdateInfo.isUpdateTypeAllowed(
                        AppUpdateType.IMMEDIATE
                    )
                ) {
                    Log.d(TAG_UPDATE, "immediate update checked")
                    //立即更新
                    startUpdate(appUpdateInfo, AppUpdateType.IMMEDIATE)
                    return@addOnSuccessListener
                }
                val stalenessDay = appUpdateInfo.clientVersionStalenessDays() ?: 0
                if (stalenessDay >= DAYS_FOR_FLEXIBLE_UPDATE && appUpdateInfo.isUpdateTypeAllowed(
                        AppUpdateType.FLEXIBLE
                    )
                ) {
                    Log.d(TAG_UPDATE, "flex update checked")
                    //灵活更新, 7天一次
                    val lastCheckFlexUpdateTime = AppPref.startFlexUpdateTime
                    val nowTimeMs = System.currentTimeMillis()
                    val days = differentDays(
                        Date(min(lastCheckFlexUpdateTime, nowTimeMs)),
                        Date(max(lastCheckFlexUpdateTime, nowTimeMs))
                    )
                    if (days < 7) {
                        return@addOnSuccessListener
                    }
                    AppPref.startFlexUpdateTime = System.currentTimeMillis()
                    Log.d(TAG_UPDATE, "start flex update")
                    startUpdate(appUpdateInfo, AppUpdateType.FLEXIBLE)
                }
            }
        }.addOnFailureListener {
            Log.i(
                TAG_UPDATE,
                "check update failed, error:${it}"
            )
        }
        appUpdateManager.registerListener(installStateUpdatedListener)
    }

    private fun startUpdate(appUpdateInfo: AppUpdateInfo, appUpdateType: Int) {
        val checkActivity = activityWeakReference?.get() ?: return
        try {
            appUpdateManager.startUpdateFlowForResult(
                appUpdateInfo,
                appUpdateType,
                checkActivity,
                REQUEST_CODE_UPDATE
            )
        } catch (e: Exception) {
            Log.e(TAG_UPDATE, "startUpdate exp:$e")
        }
    }

    private fun showCompleteUpdateDialog() {
        val checkActivity = (AppUtil.currentActivity as? FragmentActivity) ?: return
        CommonDialog.Builder()
            .message(getCompatString(R.string.common_update_downloaded))
            .positiveText(getCompatString(R.string.common_restart))
            .onPositive {
                appUpdateManager.completeUpdate()
            }
            .setShowDefaultCancel(true)
            .canceledOnTouchOutside(false)
            .build()
            .show(checkActivity.supportFragmentManager)
    }

    private fun shouldUpdateImmediate(): Boolean {
        if (forceUpdateVersionCodeSet.isEmpty()) {
            return false
        }
        val currentVersionCode = PackageUtil.getVersionCode()
        forceUpdateVersionCodeSet.forEach { versionCode ->
            if (versionCode > currentVersionCode) {
                return true
            }
        }
        return false
    }

    override fun onConfigGet(configType: GlobalConfigType, config: List<String>) {
//        if (configType == GlobalConfigType.GLOBAL_FORCE_UPDATE) {
//            Log.d(TAG_UPDATE, "onConfigGet")
//            doOnConfigGet(config)
//        }
    }

    private fun doOnConfigGet(config: List<String>) {
        runOnUiThread {
            Log.d(TAG_UPDATE, "doOnConfigGet: ${config.joinToString(",")}")
            isConfigGet = true
            forceUpdateVersionCodeSet.addAll(config.mapNotNull { it.toIntOrNull() })
            val currentActivity = AppUtil.currentActivity as? FragmentActivity ?: return@runOnUiThread
            checkUpdate(currentActivity)
        }
    }
}