package com.gh.gamecenter.download

import android.app.Application
import android.text.TextUtils
import androidx.collection.ArrayMap
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.common.filter.RegionSettingHelper.shouldThisGameBeFiltered
import com.gh.gamecenter.feature.utils.ApkActiveUtils
import com.gh.common.util.GameUtils
import com.gh.common.util.PackageUtils
import com.gh.download.DownloadManager
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.core.utils.ThirdPartyPackageHelper.getGameId
import com.gh.gamecenter.feature.entity.ApkEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.GameInstall
import com.gh.gamecenter.manager.PackagesManager
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import retrofit2.HttpException

class InstalledGameViewModel(application: Application) : AndroidViewModel(application) {

    val gameListLiveData = MutableLiveData<ArrayList<GameEntity>>()
    private val sortedList: ArrayList<GameInstall> = ArrayList()

    var isRemove = false
    val locationMap: ArrayMap<String, ArrayList<Int>> = ArrayMap()

    fun initData(list: ArrayList<GameInstall>) {
        val downloadEntityList = DownloadManager.getInstance().allSimulatorDownloadEntity
        for (entity in downloadEntityList) {
            list.add(GameInstall(id = entity.gameId))
        }
        for (gameInstall in list) {
            // 畅玩游戏不出现在常规的下载管理里
            if (gameInstall.isVGame) continue

            val ghId = PackageUtils.getMetaData(getApplication(), gameInstall.packageName, "gh_id")
            if (ghId != null && ghId != gameInstall.id) {
                gameInstall.id = ghId.toString()
            } else {
                val gameId = getGameId(gameInstall.packageName)
                if (!TextUtils.isEmpty(gameId)) {
                    gameInstall.id = gameId
                }
            }
        }
        sortedList.clear()
        sortedList.addAll(list)
        if (sortedList.isNotEmpty()) {
            val ids = ArrayList<String>()
            sortedList.sortWith { lhs: GameInstall?, rhs: GameInstall? ->
                if (rhs == null || lhs == null) {
                    0
                } else {
                    // 按安装时间排序
                    when {
                        rhs.installTime > lhs.installTime -> {
                            1
                        }
                        rhs.installTime < lhs.installTime -> {
                            -1
                        }
                        else -> {
                            0
                        }
                    }
                }
            }
            for (gameInstall in sortedList) {
                if (!ids.contains(gameInstall.id) && !shouldThisGameBeFiltered(gameInstall.id)) {
                    if (gameInstall.id != null) {
                        ids.add(gameInstall.id ?: "")
                    }
                }
            }
            initGameList(ids)
        } else {
            gameListLiveData.postValue(ArrayList())
        }
    }

    private fun initGameList(ids: List<String>) {
        val result = ArrayList<GameEntity>()
        val sequences = ArrayList<Observable<GameEntity>>()
        for (id in ids) {
            sequences.add(RetrofitManager.getInstance().api.getGameDigest(id))
        }
        Observable.mergeDelayError(sequences)
            .map(ApkActiveUtils.filterMapper)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<GameEntity?>() {
                override fun onComplete() {
                    processingData(result)
                }

                override fun onFailure(e: HttpException?) {
                    processingData(result)
                }

                override fun onNext(response: GameEntity) {
                    ApkActiveUtils.filterHideApk(response)
                    result.add(response)
                }
            })
    }

    private fun processingData(gameList: List<GameEntity>) {
        val newGameList = ArrayList<GameEntity>()
        if (gameList.isNotEmpty()) {
            var i = 0
            val size: Int = sortedList.size
            while (i < size) {
                val id = sortedList[i].id
                for (entity in gameList) {
                    if (entity.id == id) {
                        val newEntity = entity.copy()

                        // 下载管理不显示镜像游戏，不然会有奇怪的问题
                        if (entity.shouldUseMirrorInfo()) {
                            continue
                        }
                        if (newEntity.getApk().size > 1) {
                            for (apkEntity in newEntity.getApk()) {
                                val packageName: String = sortedList[i].packageName
                                if (packageName == apkEntity.packageName) {
                                    val list = ArrayList<ApkEntity>()
                                    list.add(apkEntity)
                                    newEntity.setApk(list)
                                    newEntity.dropOtherApk()
                                    if (PackageUtils.isCanPluggable(apkEntity)) {
                                        val pluggableCollection =
                                            GameUtils.getPluggableCollectionFromGameEntity(entity, packageName)
                                        if (pluggableCollection != null) {
                                            newEntity.pluggableCollection = pluggableCollection
                                        }
                                    }
                                    break
                                }
                            }
                        }

                        if (newEntity.getApk().size == 1 && (newEntity.isDualBtnModeEnabled() || newEntity.isVGamePreferred())) {
                            // 双下载按钮或畅玩优先的游戏，仅本地已安装才显示
                            if (!PackagesManager.isInstalled(newEntity.getUniquePackageName())) {
                                continue
                            }

                            newEntity.forceToBeDownloadModeOnly()
                        }

                        newGameList.add(newEntity)
                        break
                    }
                }
                i++
            }
            for (entity in newGameList) {
                entity.setEntryMap(DownloadManager.getInstance().getEntryMap(entity.name))
            }
        }
        if (newGameList.isNotEmpty()) {
            isRemove = true
            initLocationMap(newGameList)
        }
        gameListLiveData.postValue(newGameList)
    }

    private fun initLocationMap(gameList: List<GameEntity>) {
        locationMap.clear()
        var list: ArrayList<Int>?
        for (i in gameList.indices) {
            if (gameList[i].getApk().size != 0) {
                for (apk in gameList[i].getApk()) {
                    list = locationMap[apk.packageName]
                    if (list == null) {
                        list = ArrayList()
                        locationMap[apk.packageName] = list
                    }
                    list.add(i)
                }
            }
        }
    }

}