package com.gh.gamecenter.hud

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.R
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.NetworkUtils
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.halo.assistant.HaloApp
import com.lightgame.download.DownloadStatus

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

    init {
        updateStatus(STATUS_VALID)
    }

    override fun onProcess(): Boolean {
        val isOnWiFiNetwork: Boolean = NetworkUtils.isWifiConnected(HaloApp.getInstance())
        val downloadingEntitySnapshotList = DownloadManager.getInstance().allDownloadEntitySnapshots.filter {
            it.status == DownloadStatus.downloading
                    || it.status == DownloadStatus.pause
                    || it.status == DownloadStatus.subscribe
                    || it.status == DownloadStatus.timeout
                    || it.status == DownloadStatus.neterror
        }

        if (!isOnWiFiNetwork || downloadingEntitySnapshotList.isEmpty()) {
            processNext()
            return true
        } else {
            val latestDownload = downloadingEntitySnapshotList.sortedWith(compareBy { it.start }).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_wifi_download_resumed),
                    currentActivity.getString(R.string.hud_head_to_download_manager),
                    showingCallback = {
                        HeadUpDisplayLogHelper.trackDownloadResumeShow(latestDownload)
                    },
                    clickedCallback = {
                        DirectUtils.directToDownloadManager(currentActivity, "HUD")
                        HeadUpDisplayLogHelper.trackDownloadResumeClicked(latestDownload)
                    },
                    dismissCallback = {
                        processNext()
                    })
                return true
            } else {
                processNext()
                return false
            }
        }

        return false
    }

}