package com.convenient.android.common.extension

import android.content.Context
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.convenient.android.common.utils.decoration.PaddingItemDecoration

/**
 * @classname: RecyclerViewExt
 * @author: LiuXiaoLong
 * @date: 2022-07-27 PM
 * description: RecyclerView相关扩展
 */

/****** Add item padding ******/
fun RecyclerView.itemPadding(padding: Int) {
    itemPadding(padding, padding, padding, padding)
}

/****** Add item padding for top, bottom, left, right ******/
fun RecyclerView.itemPadding(top: Int, bottom: Int, left: Int = 0, right: Int = 0) {
    mutableListOf<PaddingItemDecoration>()
        .also { list ->
            for (i in 0 until itemDecorationCount) {
                when (val item = getItemDecorationAt(i)) {
                    is PaddingItemDecoration -> list.add(item)
                }
            }
        }
        .forEach { removeItemDecoration(it) }

    addItemDecoration(PaddingItemDecoration(top, bottom, left, right))
}



fun RecyclerView.onItemAdaptiveOfGrid(itemWidthDimen: Int, paddingDimen: Int = 5): Int {
    val standardPadding = context.px2dip(resources.getDimension(paddingDimen))
    val itemViewW = resources.getDimension(itemWidthDimen)
    val screenW = context.getScreenWidth()

    var column = (screenW / itemViewW).toInt().run {
        when {
            this >= 3 -> this
            else -> 3
        }
    }

    val padding = when (column) {
        1 -> context.px2dip( (screenW / column - itemViewW) / 2)
        else -> context.px2dip((screenW / column - itemViewW) / 2).run {
            when {
                (this >= standardPadding) -> this
                else -> {
                    column -= 1
                    context.px2dip( (screenW / column - itemViewW) / 2)
                }
            }
        }
    }

    layoutManager = WrapContentGridLayoutManager(context,column)
    itemPadding(padding / 2, padding / 2, padding, padding)
    return padding
}


class WrapContentGridLayoutManager constructor(context: Context?, column: Int) : GridLayoutManager(context, column) {
    override fun supportsPredictiveItemAnimations(): Boolean {
        return false
    }
}
