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.VideoEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.common.retrofit.Response
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 retrofit2.HttpException

class VideoVerifyViewModel(application: Application) : ListViewModel<VideoEntity, VideoEntity>(application) {

    private val mApi = RetrofitManager.getInstance().api
    override fun provideDataObservable(page: Int): Observable<MutableList<VideoEntity>>? {
        return mApi.getVideoVerify(UserManager.getInstance().userId, page, Config.VIDEO_PAGE_SIZE)
    }

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

    fun deleteVideo(videoId: String) {
        mApi.deleteVideo(videoId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    Utils.toast(getApplication(), "操作成功")

                    val list = mListLiveData.value ?: return
                    for (entity in list) {
                        if (entity.id == videoId) {
                            list.remove(entity)
                            mListLiveData.postValue(list)
                            break
                        }
                    }
                }

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