package com.gh.gamecenter.common.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import com.gh.gamecenter.common.R;
import com.gh.gamecenter.core.utils.DisplayUtils;

/**
 * Created by khy on 2/04/18.
 */

public class LimitHeightLinearLayout extends LinearLayout {

    private int mLimitHeight;

    public LimitHeightLinearLayout(Context context) {
        super(context);
    }

    public LimitHeightLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (attrs != null) {
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.LimitHeightScrollView);
            mLimitHeight = ta.getDimensionPixelSize(R.styleable.LimitHeightScrollView_maxHeight, DisplayUtils.dip2px(getContext(), 240));
            ta.recycle();
        } else {
            mLimitHeight = DisplayUtils.dip2px(getContext(), 240);
        }
    }

    public LimitHeightLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int totalHeight = 0;
        if (getOrientation() == VERTICAL) {
            for (int i = 0; i < getChildCount(); i++) {
                final int heightWithMargin = getChildMeasureHeightWithMargin(getChildAt(i), widthMeasureSpec, heightMeasureSpec);
                totalHeight += heightWithMargin;
            }
        } else {
            for (int i = 0; i < getChildCount(); i++) {
                final int heightWithMargin = getChildMeasureHeightWithMargin(getChildAt(i), widthMeasureSpec, heightMeasureSpec);
                if (heightWithMargin > totalHeight) {
                    totalHeight = heightWithMargin;
                }
            }
        }
        totalHeight = Math.min(totalHeight, mLimitHeight);
        int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(totalHeight, heightMode);
        setMeasuredDimension(widthMeasureSpec, maxHeightMeasureSpec);
    }

    private int getChildMeasureHeightWithMargin(View child, int widthMeasureSpec, int heightMeasureSpec) {
        measureChild(child, widthMeasureSpec, heightMeasureSpec);
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
        return child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
    }

    public void setLimitHeight(int limitHeight) {
        mLimitHeight = limitHeight;
        requestLayout();
    }
}
