package com.gh.gamecenter.hud

import com.gh.gamecenter.R
import com.gh.common.prioritychain.GlobalPriorityChainHelper
import com.gh.common.prioritychain.PriorityChainHandler
import com.gh.common.util.DirectUtils
import com.gh.download.DownloadManager
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.asVGame
import com.gh.gamecenter.common.utils.isSilentUpdate
import com.gh.gamecenter.common.utils.isSimulatorDownload
import com.gh.gamecenter.common.utils.isSimulatorGame
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.lightgame.download.DownloadStatus

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

    init {
        updateStatus(STATUS_VALID)
    }

    override fun onProcess(): Boolean {
        val downloadEntitySnapshotList = DownloadManager.getInstance().allDownloadEntitySnapshots.filter {
            it.status == DownloadStatus.done
                    && !it.asVGame()
                    && !it.isSilentUpdate()
                    && !it.isSimulatorDownload()
                    && !it.isSimulatorGame()
        }

        if (downloadEntitySnapshotList.isEmpty()) {
            processNext()
            return true
        } else {
            val latestDownload = downloadEntitySnapshotList.sortedWith(compareBy { it.end }).lastOrNull()

            val currentActivity = CurrentActivityHolder.getCurrentActivity()

            if (latestDownload != null
                && latestDownload.gameId != Constants.GHZS_GAME_ID
                && GlobalPriorityChainHelper.isThisActivityValid(currentActivity)) {
                HeadUpDisplayHelper.showHUD(
                    currentActivity!!,
                    latestDownload.icon ?: "",
                    currentActivity.getString(R.string.hud_has_pending_install_game),
                    currentActivity.getString(R.string.hud_head_to_download_manager),
                    showingCallback = {
                        HeadUpDisplayLogHelper.trackInstallationShow(latestDownload, "重启APP")
                    },
                    clickedCallback = {
                        HeadUpDisplayLogHelper.trackInstallationClick(latestDownload, "重启APP")
                        DirectUtils.directToDownloadManager(currentActivity, "HUD")
                    },
                    dismissCallback = {
                        processNext()
                    })
                return true
            } else {
                processNext()
                return false
            }
        }

        return false
    }

}