package com.gh.gamecenter.video.videomanager

import android.app.Application
import com.gh.common.constant.Config
import com.gh.common.util.ErrorHelper
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.entity.VideoDraftEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.retrofit.RetrofitManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.ResponseBody
import retrofit2.HttpException

class VideoDraftViewModel(application: Application) : ListViewModel<VideoDraftEntity, VideoDraftEntity>(application) {

    private val mApi = RetrofitManager.getInstance().api

    override fun provideDataObservable(page: Int): Observable<MutableList<VideoDraftEntity>>? {
        return mApi.getVideoDraft(UserManager.getInstance().userId, page, Config.VIDEO_PAGE_SIZE)
    }

    override fun mergeResultLiveData() {
        mResultLiveData.addSource<List<VideoDraftEntity>>(mListLiveData) { mResultLiveData.postValue(it) }
    }

    fun deleteDraft(id: String) {
        mApi.deleteVideoDraft(UserManager.getInstance().userId, id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    val list = mListLiveData.value
                    if (list != null) {
                        for (data in list) {
                            if (data.id == id) {
                                list.remove(data)
                                mListLiveData.postValue(list)
                                break
                            }
                        }
                    }
                }

                override fun onFailure(e: HttpException?) {
                    ErrorHelper.handleError(getApplication(), e?.response()?.errorBody()?.string())
                }
            })
    }
}