package com.assimilate.alltrans.curview

import android.content.Context
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.media.Image
import android.media.ImageReader
import android.os.Build
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import com.assimilate.alltrans.common.TextGraphic
import com.assimilate.alltrans.common.TextRecognitionProcessor
import com.assimilate.alltrans.common.VisionImageProcessor
import com.assimilate.alltrans.databinding.LayoutSusGlobalBinding
import com.google.mlkit.vision.text.Text
import com.google.mlkit.vision.text.chinese.ChineseTextRecognizerOptions
import java.io.IOException


class GlobalView(private val context: Context) : TextRecognitionProcessor.TextRecognitionCallback {

    private var imageProcessor: VisionImageProcessor? = null

    private val windowManager: WindowManager =
        context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    private lateinit var bindingSubGlobal: LayoutSusGlobalBinding
    private lateinit var globalView: View
    private var globalViewIsAdd: Boolean = false

    fun addGlobalView(imageReader: ImageReader) {
        // 这里还需要调整
        imageProcessor = TextRecognitionProcessor(
            context,
            ChineseTextRecognizerOptions.Builder().build(), this
        )
        bindingSubGlobal = LayoutSusGlobalBinding.inflate(LayoutInflater.from(context))
        globalView = bindingSubGlobal.root

        val layoutParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            },
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or
                    WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR,
            PixelFormat.TRANSLUCENT
        )

        layoutParams.gravity = Gravity.TOP or Gravity.LEFT

        captureScreenshot(imageReader)
        windowManager.addView(globalView, layoutParams)
        globalViewIsAdd = true

        initGlobalClick()
    }

    private fun initGlobalClick() {

        bindingSubGlobal.susGlobalClose.setOnClickListener {
            removeGlobalView()
        }
    }

     fun removeGlobalView() {
        if (globalViewIsAdd) {
            windowManager.removeView(globalView)
            globalViewIsAdd = false
        }
    }

    private fun captureScreenshot(imageReader: ImageReader) {
        val image: Image? = imageReader.acquireLatestImage()
        image?.let {
            val bitmap = imageToBitmap(it)
            image.close()
            tryReloadAndDetectInImage(bitmap)

        }
    }

    private fun imageToBitmap(image: Image): Bitmap {
        val planes = image.planes
        val buffer = planes[0].buffer
        val pixelStride = planes[0].pixelStride
        val rowStride = planes[0].rowStride
        val rowPadding = rowStride - pixelStride * image.width

        val bitmap = Bitmap.createBitmap(
            image.width + rowPadding / pixelStride,
            image.height,
            Bitmap.Config.ARGB_8888
        )
        bitmap.copyPixelsFromBuffer(buffer)
        return Bitmap.createBitmap(bitmap, 0, 0, image.width, image.height)
    }

    private fun tryReloadAndDetectInImage(bitmap: Bitmap) {
        try {
            bindingSubGlobal.susGraphicOverlay.clear()

            if (imageProcessor != null) {
                bindingSubGlobal.susGraphicOverlay.setImageSourceInfo(
                    bitmap.width,
                    bitmap.height,
                    false
                )

                imageProcessor!!.processBitmap(bitmap, bindingSubGlobal.susGraphicOverlay)

            } else {
                Log.e(
                    "SusService",
                    "Null imageProcessor, please check adb logs for imageProcessor creation error"
                )
            }
        } catch (e: IOException) {
            Log.e("SusService", "Error retrieving saved image", e)
        }
    }

    override fun onTextRecognized(text: Text, graphicOverlay: GraphicOverlay) {
        graphicOverlay.add(
            TextGraphic(
                graphicOverlay,
                text,
                true, true, "global"
            )
        )
    }

    override fun onTextFailure(e: Exception) {

    }

}
