package com.audio.record.screen.test.tool

import android.content.Context
import android.graphics.Bitmap
import android.media.Image
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat

object Extend {

    fun Image.toBitmap(): Bitmap {
        val plane = planes[0]
        val buffer = plane.buffer
        val pixelStride = plane.pixelStride
        val rowStride = plane.rowStride
        val width = this.width
        val height = this.height

        val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val bitmapBuffer = IntArray(width * height)
        var offset = 0

        for (i in 0 until height) {
            buffer.position(i * rowStride)
            for (j in 0 until width) {
                // 每次取4字节一个像素 (RGBA格式)
                val pixel = buffer.int
                bitmapBuffer[offset++] = pixel
            }
        }

        bitmap.setPixels(bitmapBuffer, 0, width, 0, 0, width, height)
        return bitmap
    }


    /**
     * @param margin PX
     */
    fun View.setMarginBottom(margin: Int) {
        val params = layoutParams as? ViewGroup.MarginLayoutParams ?: return
        params.bottomMargin = margin
        layoutParams = params
    }

    fun ImageView.setDrawableCompat(@DrawableRes resId: Int) {
        val drawable = ContextCompat.getDrawable(context, resId)
        this.setImageDrawable(drawable)
    }

    fun Int.dpToPx(context: Context): Int =
        TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, this.toFloat(),
            context.resources.displayMetrics
        ).toInt()
    fun Context.pxToDp(px: Int): Float {
        return px / resources.displayMetrics.density
    }

}