package com.gh.common.util

import com.gh.common.filter.RegionSettingHelper
import com.gh.download.DownloadManager
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.schedulers.Schedulers
import retrofit2.HttpException

/**
 * 不想写这个类的，但是与其在一个糟糕的类里插入同样的代码，我想独立写一个类相较而已还没那么糟糕
 */
object DownloadHelper {

    /**
     * 根据 game_id 和 packageName 悄悄地开启一个下载任务，如果可以的话
     * @param block 成功添加下载任务后执行的代码块
     */
    fun createABrandNewDownloadTaskQuietly(gameId: String? = "", packageName: String? = "", block: () -> Unit) {
        if (RegionSettingHelper.shouldThisGameBeFiltered(gameId)) {
            return
        }

        RetrofitManager.getInstance()
            .api
            .getGameDigest(gameId)
            .map(ApkActiveUtils.filterMapper)
            .subscribeOn(Schedulers.io())
            .subscribe(object : Response<GameEntity>() {
                override fun onResponse(response: GameEntity?) {
                    response?.let {
                        if (response.getApk().size > 1) {
                            for (apk in response.getApk()) {
                                if (packageName == apk.packageName) {
                                    DownloadManager.createDownload(
                                        HaloApp.getInstance().application,
                                        apk, response, "", EntranceConsts.ENTRANCE_RECOMMEND, "", false, null
                                    )
                                    block.invoke()
                                }
                            }
                        } else if (response.getApk().size == 1) {
                            DownloadManager.createDownload(
                                HaloApp.getInstance().application,
                                response, "", EntranceConsts.ENTRANCE_RECOMMEND, "", false, null
                            )
                            block.invoke()
                        }
                    }
                }

                override fun onFailure(e: HttpException?) {
                    e?.printStackTrace()
                    block.invoke()
                }
            })
    }

}