package com.sketch.ar.artdrawing.info

import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.graphics.Point
import android.graphics.PointF
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.Camera
import androidx.camera.core.CameraProvider
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.sketch.ar.artdrawing.MyApp
import com.sketch.ar.artdrawing.utils.ObjectBoxHelper
import com.sketch.ar.artdrawing.R
import com.sketch.ar.artdrawing.utils.CommonUtils
import androidx.core.graphics.scale
import androidx.core.net.toUri
import com.ad.toponlibrary.AdManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target

class InfoActivity : AppCompatActivity() ,OnTouchListener{
    companion object{
        val IntentKeyPath = "file_path"
    }
    private lateinit var imTab1: ImageView
    private lateinit var imTab2: ImageView
    private lateinit var imTab3: ImageView
    private lateinit var fmBack: FrameLayout
    private lateinit var previewView: PreviewView
    private lateinit var previewImage:ImageView
    private lateinit var seekBar:SeekBar


    private val startMatrix = Matrix()
    private val endMatrix = Matrix() //变化后的矩阵
    private val startPointF = PointF() //初始坐标
    private var distance = 0f //初始距离
    private var scaleMultiple = 0f //缩放倍数

    private var cameraSelector: CameraSelector? = null

    private var camera: Camera? = null
    private var imageCapture: ImageCapture? = null


    private var curBitmapPath: String? = null

    private val requestCodePermission = 1234

    //    private ImageView imPhoto;
    private var hasPermission = false
    private  var cameraProvider: ProcessCameraProvider? = null

    private var MODE = 0 //当前状态
    private val MODE_NONE: Int = 0 //无操作
    private val MODE_DRAG: Int = 1 //单指操作
    private val MODE_SCALE: Int = 2 //双指操作

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_info)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        AdManager.loadAllAd()
        AdManager.showTopOn(this) {  }
        curBitmapPath = intent.getStringExtra(IntentKeyPath)

        imTab1 = findViewById(R.id.im_tab1)
        imTab2 = findViewById(R.id.im_tab2)
        imTab3 = findViewById(R.id.im_tab3)
        fmBack = findViewById(R.id.fm_back)
        previewView = findViewById(R.id.preview)
        previewImage = findViewById(R.id.preview_image)
        seekBar = findViewById(R.id.transparency_seekbar)


        requestCameraAndImagePermission(this@InfoActivity){
            previewImage.setOnTouchListener(this@InfoActivity)
            startCamera()
        }

        imTab3.setSelected(ObjectBoxHelper.queryIsLike(curBitmapPath))
        setClick()
    }

    private fun setClick(){
        fmBack.setOnClickListener {
                finish()
        }
        imTab1.setOnClickListener {
            if (seekBar.isVisible) {
                seekBar.visibility = View.GONE
            } else if (seekBar.isGone) {
                seekBar.visibility = View.VISIBLE
            }
        }
        imTab2.setOnClickListener {
            camera?.cameraControl?.let {
                val selected: Boolean = imTab2.isSelected
                imTab2.setSelected(!selected)
                it.enableTorch(!selected)
            }?:run {
                Toast.makeText(this@InfoActivity,getString(R.string.no_camera_permission), Toast.LENGTH_SHORT).show()
            }
        }

        imTab3.setOnClickListener {
            val selected: Boolean = imTab3.isSelected
            imTab3.setSelected(!selected)
            val newSelect: Boolean = imTab3.isSelected
            if (newSelect) {
                ObjectBoxHelper.insertOrUpdateLike(curBitmapPath)
            } else {
                curBitmapPath?.let { it1 -> ObjectBoxHelper.deleteLike(it1) }
            }
        }

        seekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                val v = (seekBar.max - progress) / 10.0f
                previewImage.setAlpha(v)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
            }
        })

    }

    private fun startCamera() {
        cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
        val future = ProcessCameraProvider.getInstance(this)
        future.addListener({
            try {
                  cameraProvider = future.get()

                val preview = Preview.Builder().build()
                cameraProvider?.unbindAll()
                val builder1 = ImageCapture.Builder()
                imageCapture = builder1.build()
                camera = cameraProvider?.bindToLifecycle(
                    this,
                    cameraSelector!!, preview, imageCapture
                )

                preview.setSurfaceProvider(previewView.getSurfaceProvider())

                curBitmapPath?.let { path->
                    Log.d(MyApp.Companion.TAG, "--------path=${path}")

                    val uri = "file:///android_asset/$path".toUri()
                    previewImage.let {
                        Glide.with(this@InfoActivity)
                            .asBitmap()
                            .load(uri)
                            .override(Target.SIZE_ORIGINAL)
                            .listener(object : RequestListener<Bitmap> {
                                override fun onLoadFailed(
                                    e: GlideException?,
                                    model: Any?,
                                    target: Target<Bitmap>,
                                    isFirstResource: Boolean
                                ): Boolean {


                                    var finalBitmap =   BitmapFactory.decodeFile(path).scale(600, 600)

                                    Log.d("ltt","============onLoadFailed  ")
                                    it.setImageBitmap(finalBitmap)
                                    val width = finalBitmap.width
                                    val height = finalBitmap.height
                                    onInitPos(width.toFloat(), height.toFloat())

                                    return false
                                }

                                override fun onResourceReady(
                                    resource: Bitmap,
                                    model: Any,
                                    target: Target<Bitmap>?,
                                    dataSource: DataSource,
                                    isFirstResource: Boolean
                                ): Boolean {
                                    Log.d("ltt","============onResourceReady")
                                    it.setImageBitmap(resource)
                                    val width = resource.width
                                    val height = resource.height
                                    onInitPos(width.toFloat(), height.toFloat())

                                    return false
                                }

                            })
                            .preload()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }, ContextCompat.getMainExecutor(this))
    }
    fun requestCameraAndImagePermission(activity: Activity, onGranted: () -> Unit) {
        val permissions = mutableListOf(Manifest.permission.CAMERA)

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//            permissions.add(Manifest.permission.READ_MEDIA_IMAGES)
//        } else {
//            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
//        }

        val notGranted = permissions.filter {
            ContextCompat.checkSelfPermission(activity, it) != PackageManager.PERMISSION_GRANTED
        }

        if (notGranted.isEmpty()) {
            onGranted()
        } else {
            ActivityCompat.requestPermissions(activity, notGranted.toTypedArray(), requestCodePermission)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == requestCodePermission) {
            val notGranted = permissions.filter {
                ContextCompat.checkSelfPermission(this@InfoActivity, it) != PackageManager.PERMISSION_GRANTED
            }
            if (notGranted.isEmpty()) {
                hasPermission = true
                previewImage.setOnTouchListener(this)
                startCamera()
            } else {
                hasPermission = false
                previewImage.setOnTouchListener(null)
            }
        }

    }

    private fun onInitPos(imW: Float, imH: Float) {
        val screen: Point = CommonUtils.getScreen(this)
        val newX = screen.x / 2f - imW / 2
        val newY = screen.y / 2f - imH / 2
        startMatrix.postTranslate(newX, newY)
        previewImage.setImageMatrix(startMatrix)
    }

    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        when (event!!.action and event.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                startMatrix.set(previewImage.getImageMatrix())
                endMatrix.set(previewImage.getImageMatrix())

                startPointF[event.x] = event.y
                MODE =  MODE_DRAG
            }

            MotionEvent.ACTION_POINTER_DOWN -> {
                startMatrix.set(endMatrix)

                distance = CommonUtils.getDistance(event)

                MODE =  MODE_SCALE
            }

            MotionEvent.ACTION_MOVE -> if (MODE ==  MODE_DRAG) { //单指滑动时

                endMatrix.set(startMatrix)
                //向矩阵传入位移距离
                endMatrix.postTranslate(event.x - startPointF.x, event.y - startPointF.y)

            } else if (MODE ==  MODE_SCALE) { //双指滑动时
                //计算缩放倍数
                scaleMultiple = CommonUtils.getDistance(event) / distance
                //获取初始矩阵
                endMatrix.set(startMatrix)
                //向矩阵传入缩放倍数
                endMatrix.postScale(scaleMultiple, scaleMultiple, startPointF.x, startPointF.y)
            }

            MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP ->                 //手指离开后，重置状态
                MODE =  MODE_NONE

        }

        //事件结束后，把矩阵的变化同步到ImageView上
        previewImage.setImageMatrix(endMatrix)
        return true
    }

    override fun onDestroy() {
        super.onDestroy()
        cameraProvider?.unbindAll()
    }
}