package com.gh.gamecenter.common.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ScrollView;

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

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

public class LimitHeightScrollView extends ScrollView {

    private int mLimitHeight;

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

    public LimitHeightScrollView(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 LimitHeightScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        if (heightMode == MeasureSpec.EXACTLY) {
            heightSize = heightSize <= mLimitHeight ? heightSize
                    : mLimitHeight;
        }

        if (heightMode == MeasureSpec.UNSPECIFIED) {
            heightSize = heightSize <= mLimitHeight ? heightSize
                    : mLimitHeight;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            heightSize = heightSize <= mLimitHeight ? heightSize
                    : mLimitHeight;
        }
        int maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize,
                heightMode);
        super.onMeasure(widthMeasureSpec, maxHeightMeasureSpec);
    }
}
