package com.assimilate.alltrans.curview

import android.content.ClipData
import android.content.ClipboardManager
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.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.core.content.ContextCompat.getSystemService
import com.assimilate.alltrans.common.TextRecognitionProcessor
import com.assimilate.alltrans.common.VisionImageProcessor
import com.assimilate.alltrans.common.Widget
import com.assimilate.alltrans.databinding.LayoutSusCopyBinding
import com.google.mlkit.vision.text.chinese.ChineseTextRecognizerOptions
import java.io.IOException

class CopyTextView(private val context: Context) :
    TextRecognitionProcessor.TextRecognitionCallback {
    private var imageProcessor: VisionImageProcessor? = null


    private val windowManager: WindowManager =
        context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    private var binding: LayoutSusCopyBinding? = null
    private var rootView: View? = null
    private var recognizedText: String? = null


    fun addView(imageReader: ImageReader) {
        if (rootView != null) return

        // 这里还需要调整
        imageProcessor = TextRecognitionProcessor(
            context,
            ChineseTextRecognizerOptions.Builder().build(), true, false, this
        )

        val inflater = LayoutInflater.from(context)
        binding = LayoutSusCopyBinding.inflate(inflater, null, false)
        rootView = binding?.root

        val params = 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
        )

        windowManager.addView(rootView, params)

        captureScreenshot(imageReader)
        binding?.susGlobalClose?.setOnClickListener {
            removeView()
        }
        binding?.btSusCopyAll?.setOnClickListener {

            Log.d("gdsfsfsadf",recognizedText.toString())
            copyToClipboard(recognizedText.toString())
            removeView()
        }

    }

    fun removeView() {
        if (rootView != null) {
            windowManager.removeView(rootView)
            rootView = null
            binding = null
        }
    }


    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 {
            binding?.susGraphicOverlay?.clear()

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

                imageProcessor!!.processBitmap(bitmap, binding?.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: String) {

        recognizedText = text

    }

    // 复制到粘贴板
    private fun copyToClipboard(text: String?) {
        val tip = "Copied to clipboard!"
        val tipNull = "Text is null!"
        if (!TextUtils.isEmpty(text)) {
            val clipboardManager =
                context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val clipData = ClipData.newPlainText("targetValue", text)
            clipboardManager.setPrimaryClip(clipData)
            Toast.makeText(context, tip, Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(context, tipNull, Toast.LENGTH_SHORT).show()
        }
    }


}
