package com.gh.gamecenter.catalog

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.gamecenter.entity.CatalogEntity
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.retrofit.RetrofitManager
import com.halo.assistant.HaloApp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class SubCatalogViewModel(application: Application, private val catalogId: String) : AndroidViewModel(application) {

    private val api = RetrofitManager.getInstance().api
    var catalogs = MutableLiveData<CatalogEntity>()


    @SuppressLint("CheckResult")
    fun getSubCatalogs(primaryCatalogId: String) {
        api.getSubCatalogs(catalogId, primaryCatalogId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<CatalogEntity>() {
                override fun onSuccess(data: CatalogEntity) {
                    catalogs.postValue(data)
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    catalogs.postValue(null)
                }
            })
    }

    class Factory(private val catalogId: String) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return SubCatalogViewModel(HaloApp.getInstance().application, catalogId) as T
        }
    }
}