package com.gh.gamecenter.forum.search

import android.app.Application
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.SearchActivity
import com.gh.gamecenter.SearchType
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.entity.FollowersOrFansEntity
import com.gh.gamecenter.eventbus.EBUserFollow
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.utils.Utils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import retrofit2.HttpException

class UserSearchListViewModel(application: Application) :
    ListViewModel<FollowersOrFansEntity, FollowersOrFansEntity>(application) {
    var searchKey = ""
    var sourceEntrance = ""
    private var page = 0
    private var searchType = SearchType.DEFAULT.value


    override fun provideDataObservable(page: Int): Observable<MutableList<FollowersOrFansEntity>> {
        this.page = page
        if (page == 1) {
            NewFlatLogUtils.logSearchUser(
                SearchType.fromString(searchType).toChinese(),
                searchKey,
                sourceEntrance
            )
        }
        return RetrofitManager.getInstance().api.searchUsers(searchKey, page)
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource(mListLiveData) {
            mResultLiveData.postValue(it)
            if (page == 1) {
                SensorsBridge.trackUserSearchResultReturn(
                    GlobalActivityManager.getCurrentPageEntity().pageId,
                    GlobalActivityManager.getCurrentPageEntity().pageName,
                    sourceEntrance,
                    searchKey,
                    SearchActivity.toTrackSearchType(searchType),
                    it.isNotEmpty()
                )
            }
        }
    }

    fun updateSearchKeyAndType(searchKey: String, searchType: String) {
        this.searchKey = searchKey
        this.searchType = searchType
        load(LoadType.REFRESH)
    }

    fun follow(userId: String, callback: () -> Unit) {
        followingCommand(true, userId, callback)
    }

    fun unFollow(userId: String, callback: () -> Unit) {
        followingCommand(false, userId, callback)
    }

    private fun followingCommand(isFollow: Boolean, userId: String, callback: () -> Unit) {
        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_already_cancel)
                    }
                    callback.invoke()
                    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 getLinkPageSize(): Int {
        return mCurLoadParams.loadOffset
    }
}