package com.gh.gamecenter.fragment

import android.annotation.SuppressLint
import androidx.lifecycle.MutableLiveData
import com.gh.common.util.HomeBottomBarHelper
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.core.utils.SingletonHolder
import com.gh.gamecenter.entity.SubjectRecommendEntity
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
import retrofit2.HttpException

class MainWrapperRepository {

    private val mSensitiveApi = RetrofitManager.getInstance().api

    private val mNavBar = MutableLiveData<SubjectRecommendEntity?>()

    fun getNavBarLiveData() = mNavBar

    @SuppressLint("CheckResult")
    fun getHomeNavBar() {
        mSensitiveApi.getHomeNavBarV2(HaloApp.getInstance().channel, BuildConfig.VERSION_NAME)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BiResponse<SubjectRecommendEntity>() {
                override fun onSuccess(data: SubjectRecommendEntity) {
                    HomeBottomBarHelper.updateDefaultGameBarData(data)
                    mNavBar.postValue(data)
                }

                override fun onFailure(exception: Exception) {
                    if (exception is HttpException && exception.code() == 404) {
                        mNavBar.postValue(null)
                        HomeBottomBarHelper.updateDefaultGameBarData(SubjectRecommendEntity())
                    } else {
                        mNavBar.postValue(HomeBottomBarHelper.getDefaultGameBarData())
                    }
                }
            })
    }


    companion object : SingletonHolder<MainWrapperRepository>({ MainWrapperRepository() })
}