package com.gh.gamecenter.gamecollection.detail

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.gh.gamecenter.R
import com.gh.gamecenter.eventbus.EBUserFollow
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import retrofit2.HttpException

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

    var followLiveData = MutableLiveData<Boolean>()

    fun followingCommand(userId: String, isFollow: Boolean) {
        val observable = if (isFollow) {
            RetrofitManager.getInstance().api.postFollowing(userId)
        } else {
            RetrofitManager.getInstance().api.deleteFollowing(userId)
        }
        observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    if (isFollow) {
                        Utils.toast(getApplication(), com.gh.gamecenter.feature.R.string.concern_success)
                    } else {
                        Utils.toast(getApplication(), R.string.concern_cancel)
                    }
                    followLiveData.postValue(isFollow)
                    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)
                }
            })
    }
}