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.common.util.LogUtils
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 CatalogViewModel(application: Application, val catalogId: String, val catalogTitle: String) :
    AndroidViewModel(application) {

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

    var selectedCatalogName: String = ""
    var selectedCatalogPosition: Int = 0

    var validEntranceName: String = ""

    init {
        getCatalogs()
    }

    @SuppressLint("CheckResult")
    fun getCatalogs() {
        api.getCatalogs(catalogId)
            .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)
                }
            })
    }

    fun logAppearance() {
        LogUtils.logNewCatalogAppearanceEvent(validEntranceName, catalogTitle)
    }

    fun logSubCatalogClick(position: Int) {
        LogUtils.logSubCatalogClickEvent(validEntranceName, "${catalogTitle}_${selectedCatalogName}", position)
    }

    fun logSubCatalogContentClick(itemName: String, listPosition: Int) {
        LogUtils.logSubCatalogContentClickEvent(
            validEntranceName,
            "${catalogTitle}_${selectedCatalogName}_${itemName}",
            selectedCatalogPosition,
            listPosition
        )
    }

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