package com.gh.common.prioritychain

import androidx.fragment.app.FragmentActivity
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.gh.gamecenter.feature.entity.WelcomeDialogEntity
import com.gh.gamecenter.fragment.WelcomeDialogFragment
import com.gh.gamecenter.wrapper.MainWrapperViewModel
import com.halo.assistant.HaloApp

class WelcomeDialogHandler(priority: Int) : PriorityChainHandler(priority) {

    private var welcomeDialogEntity: WelcomeDialogEntity? = null

    fun doPreProcess(welcomeDialogEntity: WelcomeDialogEntity?) {
        this.welcomeDialogEntity = welcomeDialogEntity

        val preLoadClosure = {
            // 判断启动本次应用是否已经弹窗，不是的话弹启动弹窗
            if (HaloApp.get(MainWrapperViewModel.SHOULD_SHOW_OPENING_DIALOG, false) == null) {
                HaloApp.put(MainWrapperViewModel.SHOULD_SHOW_OPENING_DIALOG, false)
                val idealUrl = ImageUtils.getIdealImageUrl(this.welcomeDialogEntity!!.icon, 0, true) ?: ""
                ImageUtils.prefetchToDiskCache(idealUrl) { isSuccess ->
                    if (isSuccess) {
                        if (getStatus() == STATUS_PENDING) {
                            updateStatus(STATUS_VALID)
                            process()
                        } else {
                            updateStatus(STATUS_VALID)
                        }
                    } else {
                        processNext()
                    }
                }
            } else {
                processNext()
            }
        }

        if (getStatus() == STATUS_PENDING) {
            if (welcomeDialogEntity == null) {
                processNext()
            } else {
                preLoadClosure.invoke()
            }
        } else {
            if (welcomeDialogEntity == null) {
                updateStatus(STATUS_INVALID)
            } else {
                preLoadClosure.invoke()
            }
        }
    }

    override fun onProcess(): Boolean {
        val currentActivity = CurrentActivityHolder.getCurrentActivity()

        if (GlobalPriorityChainHelper.isThisActivityValid(currentActivity)) {
            when (getStatus()) {
                STATUS_VALID -> {
                    val welcomeDialog = WelcomeDialogFragment.getInstance(welcomeDialogEntity)
                    welcomeDialog.setOnDismissListener {
                        processNext()
                    }
                    welcomeDialog.show((currentActivity as FragmentActivity).supportFragmentManager, "WelcomeDialog")

                    return true
                }

                STATUS_INVALID -> {
                    processNext()
                }
            }
        }

        return false
    }

}