package com.gh.gamecenter.packagehelper

import android.app.Application
import android.text.TextUtils
import androidx.lifecycle.*
import com.gh.gamecenter.entity.GameInstall
import com.gh.gamecenter.entity.GameUpdateEntity
import com.halo.assistant.HaloApp
import kotlin.collections.set

class PackageViewModel(
    application: Application,
    private val mRepository: PackageRepository
) : AndroidViewModel(application) {

    /**
     * 过滤同包名,只显示7天下载最高的一个
     */
    val filterSameUpdateLiveData = MediatorLiveData<List<GameUpdateEntity>>()

    init {
        filterSameUpdateLiveData.addSource(mRepository.gameUpdateLiveData) {
            val updateMap = HashMap<String, GameUpdateEntity>()
            for (entity in it) {
                val updateEntity = updateMap[entity.packageName]
                if (updateEntity == null || entity.download > updateEntity.download) {
                    updateMap[entity.packageName] = entity
                }
            }
            filterSameUpdateLiveData.postValue(ArrayList(updateMap.values))
        }
    }

    /**
     * 获取可更新列表的 LiveData（数据包括当前版本，供下载管理-更新显示我的版本用）
     */
    fun getGameUpdateIncludeCurrentVersion(): MutableLiveData<List<GameUpdateEntity>> {
        val mediatorLiveData = MediatorLiveData<List<GameUpdateEntity>>()
        mediatorLiveData.addSource(mRepository.gameUpdateLiveData) {
            val decoratedList = ArrayList<GameUpdateEntity>(it)

            if (decoratedList.isNotEmpty()) {
                for (currentVersion in mRepository.currentVersionList) {
                    decoratedList.add(currentVersion)
                }
            }

            mediatorLiveData.postValue(decoratedList)
        }

        return mediatorLiveData
    }

    fun getGameInstalledLiveData(): MutableLiveData<List<GameInstall>> {
        return mRepository.gameInstalledLiveData
    }

    /**
     * 新增一个已安装的游戏
     * 只在收到安装广播时调用,不建议手动调用
     */
    fun addInstalledGame(pkgName: String?) {
        if (!TextUtils.isEmpty(pkgName)) mRepository.addInstalledGame(pkgName!!)
    }

    /**
     * 卸载一个已安装的游戏
     * 只在收到卸载广播时调用,不建议手动调用
     */
    fun addUninstalledGame(pkgName: String?) {
        if (!TextUtils.isEmpty(pkgName)) mRepository.addUninstalledGame(pkgName!!)
    }

    /**
     * 检查数据(查看数据是否初始化完成,未完成则重新加载)
     * 网络状态变更时调用
     */
    fun checkData() {
        if (mRepository.gameInstalled.size == 0
            || PackageFilterManager.hasPendingPackage()
        ) {
            mRepository.initData()
        }
    }

    class Factory : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return PackageViewModel(HaloApp.getInstance().application, PackageRepository) as T
        }
    }
}
