package com.gh.gamecenter.simulatorgame

import android.annotation.SuppressLint
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.common.simulator.SimulatorGameManager
import com.gh.gamecenter.common.utils.NetworkUtils
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.entity.SimulatorEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.gamecenter.room.AppDatabase
import com.halo.assistant.HaloApp
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers

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

    private var mSimulatorsList: List<SimulatorEntity>? = null
    private var mTypeList: List<String>? = null
    private var mResultSimulatorsList = ArrayList<SimulatorEntity>()
    private val api = RetrofitManager.getInstance().api
    var simulators = MutableLiveData<List<SimulatorEntity>>()
    private val mSimulatorGameDao = AppDatabase.getInstance().simulatorGameDao()
    var simulatorGameLoadSuccess = MutableLiveData<Boolean>()
    var isSimulatorGameFirstLoad = true

    fun getSimulators() {
        val isNetworkConnected = NetworkUtils.isNetworkConnected(HaloApp.getInstance())
        if (isNetworkConnected) {
            getSimulatorsFromNetWork()
        } else {
            getSimulatorsFromLocal()
        }
    }

    @SuppressLint("CheckResult")
    private fun getSimulatorsFromNetWork() {
        mSimulatorsList = null
        mTypeList = null
        mResultSimulatorsList.clear()
        val simulatorsSingle = api.simulators
        val deviceSimulatorTypesSingle = api.getDeviceSimulatorTypes(HaloApp.getInstance().gid)
        Single.merge(simulatorsSingle, deviceSimulatorTypesSingle)
            .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.io())
            .subscribe({
                val localSimulatorList: List<SimulatorEntity> =
                    AppDatabase.getInstance().simulatorGameDao().getSimulatorList()

                if (it.isNotEmpty()) {
                    when (it[0]) {
                        is SimulatorEntity -> mSimulatorsList = it as List<SimulatorEntity>

                        is String -> {
                            mTypeList = it as List<String>
                            // 若服务端的列表 type 与本地已有 type 的数量不一样时同步本地数据到服务端
                            if (localSimulatorList.size != mTypeList?.size) {
                                SimulatorGameManager.recordDownloadSimulatorGames()
                            }
                        }
                    }
                } else {
                    // 若网络数据为空，本地数据不为空时同步本地数据到服务端 (避免本地数据与网络数据不一致的问题)
                    if (localSimulatorList.isNotEmpty()) {
                        SimulatorGameManager.recordDownloadSimulatorGames()
                    }
                }
            }, {
                simulators.postValue(mResultSimulatorsList)
            }, {
                if (mSimulatorsList != null && mTypeList != null) {
                    mSimulatorsList?.forEach {
                        if (mTypeList!!.contains(it.type)) mResultSimulatorsList.add(it)
                    }
                }
                simulators.postValue(mResultSimulatorsList)
            })
    }

    fun hideSpecificSimulatorTypeFromMemory(type: String) {
        mResultSimulatorsList = ArrayList(mResultSimulatorsList.filter { it.type != type })
        simulators.postValue(mResultSimulatorsList)
    }

    @SuppressLint("CheckResult")
    private fun getSimulatorsFromLocal() {
        mSimulatorGameDao.getSimulatorSingle()
            .compose(singleToMain())
            .subscribe({
                simulators.postValue(it)
            }, {
                simulators.postValue(mResultSimulatorsList)
                it.printStackTrace()
            })
    }
}