package com.bc_chat.contacts.adapter

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.bc_chat.bc_base.adapter.BaseMessageAdapter
import com.bc_chat.contacts.R
import io.rong.common.RLog
import io.rong.eventbus.EventBus
import io.rong.imkit.RongContext
import io.rong.imkit.RongIM
import io.rong.imkit.fragment.ConversationListFragment
import io.rong.imkit.model.Event

import io.rong.imkit.model.UIConversation
import io.rong.imkit.widget.AsyncImageView
import io.rong.imkit.widget.ProviderContainerView
import io.rong.imkit.widget.adapter.ConversationListAdapter
import io.rong.imkit.widget.provider.IContainerItemProvider
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message

/**
 * author：Created by zhaohaoting on 2019/3/14
 * email：526309416@qq.com
 * desc：
 */
class ConversationRecyclerAdapter(var context: Context, var conversationList: List<UIConversation>? = null) : BaseMessageAdapter<UIConversation>(context, conversationList) {

    private var mOnPortraitItemClick: ConversationListAdapter.OnPortraitItemClick? = null

    override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): RecyclerView.ViewHolder {
        val itemView = LayoutInflater.from(context).inflate(R.layout.rc_item_conversation_ex, viewGroup, false)
        return ViewHolder(itemView)
    }

    override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, i: Int) {
        bindView(viewHolder as ViewHolder, i, mList[i])
    }

    override fun getItemCount(): Int {
        return count
    }

    private fun bindView(holder: ViewHolder, position: Int, data: UIConversation?) {
        if (data != null) {
            val provider = RongContext.getInstance().getConversationTemplate(data.conversationType.getName())
            if (provider == null) {
                RLog.e("ConversationListAdapter", "provider is null")
            } else {
                val view = holder.contentView.inflate<IContainerItemProvider.ConversationProvider<*>>(provider)
                provider.bindView(view, position, data)
                if (data.isTop) {
                    holder.layout.setBackgroundResource(R.drawable.rc_item_top_list_selector)
                } else {
                    holder.layout.setBackgroundResource(R.drawable.rc_item_list_selector)
                }
                val defaultId: Int = when {
                    data.conversationType == Conversation.ConversationType.GROUP -> R.drawable.rc_default_group_portrait
                    data.conversationType == Conversation.ConversationType.DISCUSSION -> R.drawable.rc_default_discussion_portrait
                    else -> R.drawable.rc_default_portrait
                }
                holder.layout.setOnClickListener { v1 -> mOnPortraitItemClick?.onPortraitItemClick(v1, data) }
                holder.layout.setOnLongClickListener { v -> mOnPortraitItemClick?.onPortraitItemLongClick(v, data)!! }
                when {
                    data.conversationGatherState -> holder.leftImageView.setAvatar(null, defaultId)
                    data.iconUrl != null -> holder.leftImageView.setAvatar(data.iconUrl.toString(), defaultId)
                    else -> holder.leftImageView.setAvatar(null, defaultId)
                }

                if (data.unReadMessageCount > 0) {
                    if (data.unReadMessageCount > 99) {
                        holder.rightUnReadView.text = "99+"
                    } else {
                        holder.rightUnReadView.text = Integer.toString(data.unReadMessageCount)
                    }
                    holder.rightUnReadView.visibility = View.VISIBLE
                } else {
                    holder.rightUnReadView.visibility = View.GONE
                }

                val content = data.messageContent
                if (content != null && content.isDestruct) {
                    RongIMClient.getInstance().getMessage(data.latestMessageId, object : RongIMClient.ResultCallback<Message>() {

                        override fun onSuccess(message: Message?) {
                            if (message == null) {
                                EventBus.getDefault().post(Event.MessageDeleteEvent(data.latestMessageId))
                            } else if (message.readTime > 0L) {
                                val readTime = message.readTime
                                val serverTime = System.currentTimeMillis() - RongIMClient.getInstance().deltaTime
                                val delay = message.content.destructTime - (serverTime - readTime) / 1000L
                                if (delay > 0L) {
                                    RongIM.getInstance().createDestructionTask(message, null, ConversationListFragment.TAG)
                                } else {
                                    EventBus.getDefault().post(Event.DestructionEvent(message))
                                }
                            }
                        }

                        override fun onError(e: RongIMClient.ErrorCode) {}
                    })
                }
            }
        }
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var layout: View = itemView.findViewById(R.id.rc_item_conversation)
        var rightUnReadView: TextView = itemView.findViewById(R.id.tv_unread)
        var leftImageView: AsyncImageView = itemView.findViewById(R.id.rc_left)
        var contentView: ProviderContainerView = itemView.findViewById(R.id.rc_content)
    }

    fun setOnPortraitItemClick(onPortraitItemClick: ConversationListAdapter.OnPortraitItemClick?) {
        this.mOnPortraitItemClick = onPortraitItemClick
    }

}
