package mtp.polymer.com.autowidget.recyclerview


import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import cn.muchinfo.rma.view.autoWidget.autoSize


/**
 * adapter中调用onCreateViewHolder, onBindViewHolder
 */
class CardAdapterHelper {
    private var mPagePadding = autoSize(15)
    private var mShowLeftCardWidth = autoSize(15)
    private var parent: ViewGroup? = null

    fun onCreateViewHolder(parent: ViewGroup, itemView: View) {
        this.parent = parent
        val lp = itemView.layoutParams as RecyclerView.LayoutParams
        lp.width = parent.width - (mPagePadding + mShowLeftCardWidth).times(2)
        itemView.layoutParams = lp
    }

    fun onBindViewHolder(itemView: View, position: Int, itemCount: Int) {
        parent?.let {
            (itemView.layoutParams as? RecyclerView.LayoutParams)?.let { lp ->
                val cardWidth = it.width - mPagePadding.plus(mShowLeftCardWidth).times(2)
                when {
                    itemCount == 1 -> lp.width = it.width.minus((mPagePadding).times(2))
                    lp.width != cardWidth -> lp.width = cardWidth
                }
                itemView.layoutParams = lp
            }
        }

        val padding = mPagePadding
        itemView.setPadding(padding, 0, padding, 0)
        val leftMarin = if (position == 0 || itemCount == 1) padding else 0
        val rightMarin = when {
            itemCount == 1 -> padding
            position == itemCount - 1 -> padding.plus(mShowLeftCardWidth)
            else -> 0
        }
        setViewMargin(itemView, leftMarin, 0, rightMarin, 0)
    }

    private fun setViewMargin(view: View, left: Int, top: Int, right: Int, bottom: Int) {
        val lp = view.layoutParams as ViewGroup.MarginLayoutParams
        if (lp.leftMargin != left || lp.topMargin != top || lp.rightMargin != right || lp.bottomMargin != bottom) {
            lp.setMargins(left, top, right, bottom)
            view.layoutParams = lp
        }
    }

    fun setPagePadding(pagePadding: Int) {
        mPagePadding = pagePadding
    }

    fun setShowLeftCardWidth(showLeftCardWidth: Int) {
        mShowLeftCardWidth = showLeftCardWidth
    }
}
