package com.gh.gamecenter.message

import android.app.Application
import com.gh.gamecenter.common.baselist.ListViewModel
import com.gh.gamecenter.entity.MessageKeFuEntity
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.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject

class KeFuViewModel(application: Application) : ListViewModel<MessageKeFuEntity, MessageKeFuEntity>(application) {

    override fun provideDataObservable(page: Int): Observable<MutableList<MessageKeFuEntity>>? {
        return RetrofitManager.getInstance().api.getMessageKeFuData(UserManager.getInstance().userId, page)
    }

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

    fun postMessageRead(messageId: String) {

        // 更新本地数据以及页面
        val listData = mListLiveData.value
        if (listData != null) {
            for (entity in listData) {
                if (messageId == entity.id) {
                    entity.isRead = true
                    mListLiveData.postValue(listData)
                    break
                }
            }
        }

        // 后端同步
        val jsonObject = JSONObject()
        jsonObject.put("type", "system_message")
        val body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())
        RetrofitManager.getInstance().api.postMessageRead(UserManager.getInstance().userId, messageId, body)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
            })
    }

    fun deleteMessage(messageId: String) {
        RetrofitManager.getInstance().api
            .deleteKaiFuMessage(UserManager.getInstance().userId, messageId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<ResponseBody>() {
                override fun onResponse(response: ResponseBody?) {
                    val listData = mListLiveData.value
                    listData?.let {
                        val iterator = it.iterator()
                        while (iterator.hasNext()) {
                            val data = iterator.next()
                            if (data.id == messageId) {
                                it.remove(data)
                                mListLiveData.postValue(listData)
                                break
                            }
                        }
                    }
                }
            })
    }
}