package com.gh.gamecenter.common.view

import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import com.gh.gamecenter.common.R
import com.gh.gamecenter.common.utils.dip2px

class MaxHeightLinearLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    private var mMaxHeight = 0

    init {
        if (attrs != null) {
            val ta = context.obtainStyledAttributes(attrs, R.styleable.LimitHeightScrollView)
            mMaxHeight = ta.getDimensionPixelSize(
                R.styleable.LimitHeightScrollView_maxHeight,
                240F.dip2px()
            )
            ta.recycle()
        } else {
            mMaxHeight = 240F.dip2px()
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var heightSize = MeasureSpec.getSize(heightMeasureSpec)
        if (mMaxHeight != 0 && (heightMode == MeasureSpec.EXACTLY || heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED)) {
            heightSize = heightSize.coerceAtMost(mMaxHeight)
        }
        val maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
            heightSize,
            heightMode
        )
        super.onMeasure(widthMeasureSpec, maxHeightMeasureSpec)
    }

    fun setMaxHeight(maxHeight: Int) {
        mMaxHeight = maxHeight
        requestLayout()
    }
}
