package com.convenient.android.common.extension

import android.content.Context
import android.os.Build
import android.view.View
import android.view.ViewTreeObserver
import androidx.annotation.ColorRes
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat

/**
 * @classname:ContextExtensions
 * @author: LiuXiaoLong
 * @date: 2022/7/27
 * description:
 */


/**
 * 获取资源中的颜色
 */
fun Context.getColor(@ColorRes colorResId : Int) : Int{
    return ContextCompat.getColor(this, colorResId)
}


/****** 获取View onGlobalLayout Start ******/
/****** Register a callback to be invoked when the global layout state or the visibility of views within the view tree changes ******/
inline fun View.onGlobalLayout(crossinline callback: () -> Unit) = with(viewTreeObserver) {
    addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
        override fun onGlobalLayout() {
            removeOnGlobalLayoutListener(this)
            callback()
        }
    })
}

/****** Register a callback to be invoked after the view is measured ******/
inline fun View.afterMeasured(crossinline callback: View.() -> Unit) {
    viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
        override fun onGlobalLayout() {
            if (measuredWidth > 0 && measuredHeight > 0) {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
                callback()
            }
        }
    })
}
