package com.bc_chat.contacts.dataSource

import com.zhaohaoting.framework.abs.datasource.RxCustomDataSource
import com.zhaohaoting.framework.mvchelper.mvc.ResponseSender
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.rong.imkit.model.UIMessage
import io.rong.imlib.RongCommonDefine
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import java.lang.Exception
import java.util.*
import kotlin.collections.ArrayList

/**
 * author：Created by zhaohaoting on 2019/2/27
 * email：526309416@qq.com
 * desc：
 */
class ChatRecordDataSource(var conversationType: Conversation.ConversationType?, var mTargetId: String?, var oldestMessageId: Long? = -1) : RxCustomDataSource<List<UIMessage>>() {

    private val objectNames = ArrayList<String>()

    init {
        objectNames.add("RC:TxtMsg")
        objectNames.add("RC:VcMsg")
        objectNames.add("RC:ImgMsg")
        objectNames.add("RC:ImgTextMsg")
        objectNames.add("RC:FileMsg")
        objectNames.add("RC:LBSMsg")
        objectNames.add("RC:SightMsg")
        objectNames.add("RC:PSImgTxtMsg")
        objectNames.add("RC:PSMultiImgTxtMsg")
    }


    override fun loadListFromNetWork(params: HashMap<String, Any>?): Flowable<List<UIMessage>> {
        return Flowable.create({
            if (nextPage == 1) {
                oldestMessageId = -1
            }
            RongIMClient.getInstance().getHistoryMessages(conversationType, mTargetId, objectNames.toList(), oldestMessageId!!, 500, RongCommonDefine.GetMessageDirection.FRONT, object : RongIMClient.ResultCallback<List<Message>>() {

                override fun onSuccess(p0: List<Message>?) {
                    var mMessages: ArrayList<UIMessage> = ArrayList()
                    if (p0 != null && p0.size > 0) {
                        p0.forEach {
                            mMessages.add(UIMessage.obtain(it))
                        }
                    }
                    it.onNext(mMessages)
                }

                override fun onError(p0: RongIMClient.ErrorCode?) {
                    it.onError(Exception("加载失败"))
                }
            })
        }, BackpressureStrategy.BUFFER)
    }

    override fun loadSubscriberOnNext(data: List<UIMessage>?, sender: ResponseSender<List<UIMessage>>?) {
        sender?.sendData(data)
    }
}
