package com.adealink.weparty.im.list.widget

import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.adealink.weparty.im.list.adapter.SessionListAdapter
import com.tencent.qcloud.tuikit.timcommon.component.CustomLinearLayoutManager
import com.tencent.qcloud.tuikit.tuiconversation.presenter.ConversationPresenter

class SessionListLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr), ISessionListLayout {
    private var mAdapter: SessionListAdapter? = null
    private var presenter: ConversationPresenter? = null

    init {
        isLayoutFrozen = false
        setItemViewCacheSize(0)
        setHasFixedSize(true)
        setFocusableInTouchMode(false)
        val linearLayoutManager = CustomLinearLayoutManager(context)
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL)
        setLayoutManager(linearLayoutManager)
        val animator = itemAnimator as SimpleItemAnimator?
        animator?.supportsChangeAnimations = false
    }

    fun setPresenter(presenter: ConversationPresenter?) {
        this.presenter = presenter
    }

    override fun setAdapter(adapter: Adapter<*>?) {
        super.setAdapter(adapter)
        this.mAdapter = adapter as? SessionListAdapter
    }

    override fun disableItemUnreadDot(flag: Boolean) {
//        mAdapter!!.disableItemUnreadDot(flag)
    }

    override fun onScrollStateChanged(state: Int) {
        super.onScrollStateChanged(state)
        if (state == SCROLL_STATE_IDLE) {
            val layoutManager = layoutManager as LinearLayoutManager?
            if (layoutManager == null) {
                return
            }
            mAdapter?.let { adapter ->
                val lastPosition = layoutManager.findLastCompletelyVisibleItemPosition()
                if (lastPosition == adapter.itemCount - 1 && !this.isLoadCompleted) {
                    adapter.onLoadingStateChanged(true)
                    presenter?.loadMoreConversation()
                }
            }
        }
    }

    fun loadConversation() {
        presenter?.loadMoreConversation()
    }

    fun loadMarkedConversation() {
        presenter?.loadMarkedConversation()
    }

    val isLoadCompleted: Boolean
        get() {
            return presenter?.isLoadFinished ?: false
        }
}