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

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.base.browserwhite.ui.activity.webbrowser.WebBrowserActivity
import com.base.browserwhite.ui.fragment.HomeFragment.Companion.isMatchesUrl
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.barcode.common.Barcode.FORMAT_AZTEC
import com.google.mlkit.vision.barcode.common.Barcode.FORMAT_CODABAR
import com.google.mlkit.vision.common.InputImage


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

    private val TAG = "QRImageAnalyzer"

    var action: ((qrCodeValue: String) -> 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
            LogEx.logDebug(TAG, "valueType=$valueType")
            when (valueType) {

                Barcode.FORMAT_QR_CODE, FORMAT_CODABAR, FORMAT_AZTEC -> {
                    val qrCodeValue = barcode.rawValue ?: ""
                    LogEx.logDebug(TAG, "qrCodeValue=${qrCodeValue}")
                    if (isMatchesUrl(qrCodeValue) or qrCodeValue.startsWith("http") or qrCodeValue.startsWith("https")) {
                        action?.invoke(qrCodeValue)
                    }
                }
            }
        }
    }

    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 ->
                // 处理失败情况
            }
    }
}