package com.bc_chat.contacts.dataSource

import com.bc_chat.im.entity.TimeMessage
import com.zhaohaoting.framework.abs.datasource.RxCustomDataSource
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
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.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 * author：Created by zhaohaoting on 2019/2/27
 * email：526309416@qq.com
 * desc：
 */
class ChatPictureDataSource(var conversationType: Conversation.ConversationType?, var mTargetId: String?, var time: Long? = System.currentTimeMillis(), var headId: Int? = 0) : RxCustomDataSource<List<TimeMessage>>() {

    override fun loadListFromNetWork(params: HashMap<String, Any>?): Flowable<List<TimeMessage>> {
        return Flowable.create({
            if (nextPage == 1) {
                time = System.currentTimeMillis()
                headId = 0
            }
            RongIMClient.getInstance().getHistoryMessages(conversationType, mTargetId, arrayOf("RC:ImgMsg","RC:SightMsg").toList(), time!!, 50, RongCommonDefine.GetMessageDirection.FRONT, object : RongIMClient.ResultCallback<List<Message>>() {

                override fun onSuccess(p0: List<Message>?) {
                    var mMessages: ArrayList<TimeMessage> = ArrayList()
                    if (p0 != null && p0.size > 0) {
                        p0.forEach {
                            val time = f.format(it.sentTime)
                            //如果是第一次或者是不同的头部ID了。说明时间不同了。生产一个标题头部
                            if (headId == 0 || headId != time.hashCode()) {
                                headId = time.hashCode()
                                val timeMsg = TimeMessage(1)
                                timeMsg.time = time
                                mMessages.add(timeMsg)
                            }
                            val chatMsg = TimeMessage()
                            chatMsg.message = it
                            chatMsg.time = time
                            mMessages.add(chatMsg)
                        }
                    }
                    it.onNext(mMessages)
                }

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

    private val f = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)

}
