package com.gh.gamecenter.feature.utils

import android.text.TextUtils
import com.therouter.TheRouter
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.core.provider.IUserManagerProvider
import com.gh.gamecenter.feature.eventbus.EBConcernChanged
import com.gh.gamecenter.feature.retrofit.RetrofitManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import retrofit2.HttpException

/**
 * Created by khy on 2016/8/24.
 * croncern 工具类
 */
object ConcernUtils {

    private val mUserManager = TheRouter.get(IUserManagerProvider::class.java)

    /**
     * autoConcern:是否自动关注'关联关注'
     */
    fun postConcernGameId(
        gameId: String,
        listener: OnConcernListener?,
        autoConcern: Boolean = false
    ) {
        val mode = if (autoConcern) "auto" else "manual"

        val userId = mUserManager?.getUserId()
        if (TextUtils.isEmpty(userId)) return

        RetrofitManager.getInstance().api
            .postConcern(userId!!, gameId, mode)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    listener?.onSuccess()
                    EventBus.getDefault().post(EBConcernChanged(gameId, true))
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    listener?.onError()
                }
            })
    }

    fun deleteConcernData(gameId: String, listener: OnConcernListener?) {
        val userId = mUserManager?.getUserId()
        if (TextUtils.isEmpty(userId)) return

        RetrofitManager.getInstance().api
            .deleteConcern(userId!!, gameId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    super.onResponse(response)
                    listener?.onSuccess()
                    EventBus.getDefault().post(EBConcernChanged(gameId, false))
                }

                override fun onFailure(e: HttpException?) {
                    super.onFailure(e)
                    listener?.onError()
                }
            })
    }

    interface OnConcernListener {
        fun onSuccess()
        fun onError()
    }

}

