package com.gh.gamecenter.gamecollection.hotlist

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.entity.LinkEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.observableToMain
import com.gh.gamecenter.entity.GameCollectionPlayerCreationEntity
import com.gh.gamecenter.entity.PlayerCreationItem
import com.gh.gamecenter.eventbus.EBUserFollow
import com.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.SingleEmitter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import retrofit2.HttpException

class GameCollectionPlayerCreationViewModel(application: Application) :
    ListViewModel<PlayerCreationItem, PlayerCreationItem>(application) {
    private val mApi = RetrofitManager.getInstance().api
    var isWeek = true // true：周榜、false：月榜
    val topLinkLiveData = MutableLiveData<LinkEntity>()

    override fun provideDataObservable(page: Int): Observable<MutableList<PlayerCreationItem>>? = null

    override fun provideDataSingle(page: Int): Single<MutableList<PlayerCreationItem>> {
        return Single.create {
            if (page == 1) {
                getGameCollectionPlayerCreation(it)
            } else {
                it.onSuccess(arrayListOf())
            }
        }
    }

    private fun getGameCollectionPlayerCreation(emitter: SingleEmitter<MutableList<PlayerCreationItem>>) {
        mApi.getGameCollectionPlayerCreation(isWeek)
            .compose(observableToMain())
            .subscribe(object : Response<GameCollectionPlayerCreationEntity>() {
                override fun onResponse(response: GameCollectionPlayerCreationEntity?) {
                    super.onResponse(response)
                    response?.run {
                        tipLink?.let { topLinkLiveData.postValue(it) }
                        data?.let { emitter.onSuccess(ArrayList(it)) }
                    }
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    mLoadStatusLiveData.postValue(LoadStatus.INIT_FAILED)
                }
            })
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) {
            mResultLiveData.postValue(it)
        }
    }

    fun followingCommand(userId: String, isFollow: Boolean, onSuccess: () -> Unit) {
        val observable = if (isFollow) {
            mApi.postFollowing(userId)
        } else {
            mApi.deleteFollowing(userId)
        }
        observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    onSuccess.invoke()
                    if (isFollow) {
                        Utils.toast(getApplication(), com.gh.gamecenter.feature.R.string.concern_success)
                    } else {
                        Utils.toast(getApplication(), R.string.concern_cancel)
                    }
                    EventBus.getDefault().post(EBUserFollow(userId, isFollow))
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    Utils.toast(getApplication(), com.gh.gamecenter.feature.R.string.loading_failed_hint)
                }
            })
    }

    fun switchType(isWeek: Boolean, callback: () -> Unit) {
        if (this.isWeek == isWeek) return

        this.isWeek = isWeek
        mApi.getGameCollectionPlayerCreation(isWeek)
            .compose(observableToMain())
            .subscribe(object : Response<GameCollectionPlayerCreationEntity>() {
                override fun onResponse(response: GameCollectionPlayerCreationEntity?) {
                    super.onResponse(response)
                    callback.invoke()
                    response?.data?.let {
                        mListLiveData.postValue(ArrayList(it))
                    }
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    callback.invoke()
                    mLoadStatusLiveData.postValue(LoadStatus.INIT_FAILED)
                }
            })
    }
}