package com.gh.common.chain

import android.app.Activity
import android.content.Context
import com.gh.common.util.DialogUtils
import com.gh.common.util.DirectUtils
import com.gh.common.util.PackageChangeHelper
import com.gh.common.util.TempCertificationUtils
import com.gh.gamecenter.feature.entity.GameEntity

class LandPageAddressHandler : DownloadChainHandler() {

    override fun handleRequest(context: Context, gameEntity: GameEntity, asVGame: Boolean) {
        if (gameEntity.isLandPageAddressDialog()) {
            TempCertificationUtils.checkCertificationBeforeAction(gameEntity) {
                if (context is Activity && context.isFinishing) {
                    // 当前 context 已经无效，不需要再传递执行下去了
                    return@checkCertificationBeforeAction
                }

                DialogUtils.showLandPageAddressDialog(context, gameEntity) {// 跳转第三方落地页
                    if (gameEntity.isLandPageAddressDialogShowOnly()) {
                        if (hasNext()) {
                            getNext()?.handleRequest(context, gameEntity, asVGame)
                        } else {
                            processEndCallback?.invoke(asVGame, null)
                        }
                    } else {
                        val packageName = gameEntity.getApk().firstOrNull()?.packageName
                        if (packageName?.isNotEmpty() == true) {
                            PackageChangeHelper.addInstallPendingPackage(packageName)
                        }
                        DirectUtils.directToExternalBrowser(context, gameEntity.landPageAddressDialog!!.link!!)
                    }
                }
            }
        } else {
            if (hasNext()) {
                getNext()?.handleRequest(context, gameEntity, asVGame)
            } else {
                processEndCallback?.invoke(asVGame, null)
            }
        }
    }
}