package com.gh.gamecenter.common.view

import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.widget.RelativeLayout
import com.gh.gamecenter.common.R

class MaterializedRelativeLayout : RelativeLayout {

    private var mConsumeWindowInset: Boolean = false

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.MaterializedRelativeLayout)
        mConsumeWindowInset = ta.getBoolean(R.styleable.MaterializedRelativeLayout_consumeWindowInsets, false)
        ta.recycle()
    }

    /**
     * 将 windowInsets 传递给子 view [https://medium.com/androiddevelopers/why-would-i-want-to-fitssystemwindows-4e26d9ce1eec#.raoa9t506]
     */
    override fun onAttachedToWindow() {
        super.onAttachedToWindow()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setOnApplyWindowInsetsListener { _, insets ->
                if (mConsumeWindowInset) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
                        insets.replaceSystemWindowInsets(
                            insets.systemWindowInsetLeft,
                            0,
                            insets.systemWindowInsetRight,
                            insets.systemWindowInsetBottom
                        )
                        insets.consumeSystemWindowInsets()
                    }
                } else {
                    val childCount = childCount
                    for (index in 0 until childCount) {
                        getChildAt(index).dispatchApplyWindowInsets(insets)
                    }
                }
                insets
            }
        }
    }

}