package com.base.browserwhite.ui.activity.scanqrc

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.widget.Toast
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.base.browserwhite.utils.LogEx
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage


//图形分析器
class QRImageAnalyzer() : ImageAnalysis.Analyzer {

    private val TAG = "QRImageAnalyzer"

    var parseAction: ((qrCodeValue: String, valueType: Int) -> Unit)? = null

    //如需仅检测 Aztec 码和 QR 码
    private val options = BarcodeScannerOptions.Builder().setBarcodeFormats(
        Barcode.FORMAT_QR_CODE, Barcode.FORMAT_AZTEC
    ).build()

    //获取解析器
    private val detector = BarcodeScanning.getClient(options)

    @SuppressLint("UnsafeOptInUsageError")
    override fun analyze(imageProxy: ImageProxy) {
        val mediaImage = imageProxy.image
        if (mediaImage != null) {
            val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
            detector.process(image).addOnSuccessListener { barcodeList ->

//                    barcodeList.forEach {
//                        LogEx.logDebug(TAG, "rawValue=${it.rawValue}")
//                    }
                handleBarcodeList(barcodeList)

            }.addOnFailureListener {
                LogEx.logDebug(TAG, "OnFailure")
            }.addOnCompleteListener {
                LogEx.logDebug(TAG, "OnComplete")
                imageProxy.close()
            }
        } else {
            imageProxy.close()
        }
    }

    private fun handleBarcodeList(
        barcodeList: List<Barcode>,
    ) {

        if (barcodeList.size == 1) {
            val barcode = barcodeList[0]
            val valueType = barcode.valueType
            val qrCodeValue = barcode.rawValue ?: ""
//            Barcode.FORMAT_QR_CODE, FORMAT_CODABAR, FORMAT_AZTEC, TYPE_TEXT
            LogEx.logDebug(TAG, "valueType=$valueType")
            parseAction?.invoke(qrCodeValue, valueType)
        }
    }

    fun processImage(context: Context, bitmap: Bitmap) {
        val image = InputImage.fromBitmap(bitmap, 0)
        val barcodeScanner = BarcodeScanning.getClient(options)

        barcodeScanner.process(image)
            .addOnSuccessListener { barcodes ->
                handleBarcodeList(barcodes)
            }
            .addOnFailureListener { exception ->
                // 处理失败情况
//                LogEx.logDebug(TAG,"$exception")
                Toast.makeText(context, "Unable to parse QR code", Toast.LENGTH_SHORT).show()
            }
    }
}