package com.gh.gamecenter.feedback.view.qa

import android.annotation.SuppressLint
import android.app.Application
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.common.utils.observableToMain
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.feedback.entity.HelpEntity
import com.gh.gamecenter.feedback.retrofit.RetrofitManager
import io.reactivex.Observable
import io.reactivex.Single
import retrofit2.HttpException

class HelpQaDefaultViewModel(application: Application) : ListViewModel<HelpEntity, HelpEntity>(application) {
    private val mApi = RetrofitManager.getInstance().newApi

    override fun provideDataObservable(page: Int): Observable<List<HelpEntity>>? = null

    @SuppressLint("CheckResult")
    override fun provideDataSingle(page: Int): Single<List<HelpEntity>> {
        return Single.create {
            if (page == 1) {
                mApi.getOthersSearch()
                    .compose(singleToMain())
                    .subscribe(object : BiResponse<List<HelpEntity>>() {
                        override fun onSuccess(data: List<HelpEntity>) {
                            it.onSuccess(data)
                        }

                        override fun onFailure(exception: Exception) {
                            super.onFailure(exception)
                            mLoadStatusLiveData.postValue(LoadStatus.INIT_FAILED)
                        }
                    })
            } else {
                it.onSuccess(emptyList())
            }
        }
    }

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