package com.gh.gamecenter.download

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.gh.common.filter.RegionSettingHelper
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.core.utils.RandomUtils
import com.gh.gamecenter.entity.AdConfig
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp

class AdGameViewModel(application: Application, private val mAdConfig: AdConfig) :
    AndroidViewModel(application) {
    private val mApi = RetrofitManager.getInstance().newApi
    val gameListLiveData = MutableLiveData<List<GameEntity>>()

    init {
        getAdGameList()
    }

    @SuppressLint("CheckResult")
    fun getAdGameList() {
        val pageSize = mAdConfig.ownerAd?.adSource?.gamesIds?.size ?: 20
        val codeId = mAdConfig.ownerAd?.id
        val paramsMap = mapOf("page" to "1,$pageSize", "code_id" to codeId)
        mApi.getAdGames(mAdConfig.id, paramsMap)
            .compose(singleToMain())
            .subscribe(object : BiResponse<List<GameEntity>>() {
                override fun onSuccess(data: List<GameEntity>) {
                    val filterGameList = RegionSettingHelper.filterGame(data)
                    val resultList = ArrayList<GameEntity>()
                    if (filterGameList.isNotEmpty()) {
                        val indexes = RandomUtils.getRandomArray(filterGameList.size, filterGameList.size)
                        for (index in indexes) {
                            resultList.add(filterGameList[index].apply {
                                adIconActive = mAdConfig.ownerAd?.adSource?.adIconActive ?: false
                                adSpaceId = mAdConfig.id
                                gameAdSourceId = mAdConfig.ownerAd?.id ?: ""
                            })
                        }
                    }
                    gameListLiveData.postValue(resultList)
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    gameListLiveData.postValue(emptyList())
                }
            })
    }


    class Factory(private val mAdConfig: AdConfig) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return AdGameViewModel(HaloApp.getInstance(), mAdConfig) as T
        }
    }
}