package com.apps.quicksketchtrace.activity

import MainViewModel
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.PointF
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.SeekBar
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.Camera
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.apps.quicksketchtrace.activity.EachCategoryActivity
import com.apps.quicksketchtrace.ad.TPManager
import com.apps.quicksketchtrace.databinding.ActivityDrawPictureBinding
import com.apps.quicksketchtrace.util.OpenConvert
import com.google.common.util.concurrent.ListenableFuture


class StartDrawActivity : AppCompatActivity(),View.OnTouchListener {
    private lateinit var binding:ActivityDrawPictureBinding
    private lateinit var defaultBackCamera: CameraSelector
    private lateinit var imageCapture: ImageCapture
    private lateinit var camera: Camera
    private var fullName: String = ""
    private var isShow=false
    private lateinit var requestPermissionLauncher: ActivityResultLauncher<String>
    private lateinit var mainViewModel: MainViewModel

    private var MODE = 0 // 当前状态
    private val MODE_NONE = 0 // 无操作
    private val MODE_DRAG = 1 // 单指操作
    private val MODE_SCALE = 2 // 双指操作
    private val startMatrix = Matrix()
    private val endMatrix = Matrix() // 变化后的矩阵
    private val startPointF = PointF() // 初始坐标
    private var distance = 0f // 初始距离
    private var scaleMultiple = 0f // 缩放倍数
    companion object{
        const val PATH_KEY="path"
    }
    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding=ActivityDrawPictureBinding.inflate(layoutInflater)
        setContentView(binding.root)
        mainViewModel=ViewModelProvider(this)[MainViewModel::class.java]
        window.statusBarColor = Color.TRANSPARENT
        window.decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        defaultBackCamera= CameraSelector.DEFAULT_BACK_CAMERA
        binding.imgCard.setOnTouchListener(this)
        binding.llAlpha.visibility=View.GONE
        binding.imgAlpha.isSelected=false
        binding.imgAlpha.setOnClickListener {
            if(!isShow){
                binding.llAlpha.visibility=View.VISIBLE
                binding.imgAlpha.isSelected=true
                isShow=true
            }else{
                binding.llAlpha.visibility=View.GONE
                binding.imgAlpha.isSelected=false
                isShow=false
            }
        }
        requestPermissionLauncher=registerForActivityResult(ActivityResultContracts.RequestPermission()){
            granted->
            if(granted){
                startCamera()
            }else{
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
            }
        }
        TPManager.showTPAD(this@StartDrawActivity) {  }
        init()
    }
    private fun init(){
        fullName=intent.getStringExtra(PATH_KEY)?:""
        Log.d("YYYYYY", fullName+"")
        binding.back.setOnClickListener {

            TPManager.showTPAD(this@StartDrawActivity) {
                finish()
            }

        }
        mainViewModel.isLocal.observe(this){isLike->
            binding.imgLike.isSelected=isLike
        }
        mainViewModel.checkIsLocal(fullName)
        binding.imgLike.setOnClickListener { v->
            val selected = v.isSelected
            binding.imgLike.isSelected=!selected
            if(!selected){
                mainViewModel.addLocal(fullName)
            }else{
                mainViewModel.deleteLocalPath(fullName)
            }
        }
        binding.seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                val alpha=(seekBar.max-progress)/10f
                binding.imgCard.alpha=alpha
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }

        })
        val cameraPermit=Manifest.permission.CAMERA
        if(ContextCompat.checkSelfPermission(this,cameraPermit)!=PackageManager.PERMISSION_GRANTED){
            requestPermissionLauncher.launch(cameraPermit)
        }else{
            startCamera()
        }

    }



    private fun startCamera() {
        val future: ListenableFuture<ProcessCameraProvider> = ProcessCameraProvider.getInstance(this)
        future.addListener({
            try {
                val cameraProvider = future.get()
                val preview = Preview.Builder().build()
                cameraProvider.unbindAll()
                val builder = ImageCapture.Builder()
                imageCapture = builder.build()
                camera = cameraProvider.bindToLifecycle(this, defaultBackCamera, preview, imageCapture)
                preview.surfaceProvider = binding.preview.surfaceProvider
                if (fullName.isNotEmpty()) {
                    val bitmap = OpenConvert.loadBitmapFromAssets(this, fullName)
                    if(bitmap==null){
                        Log.d("YYYYYYYY","return null")
                        val decodedBitmap = BitmapFactory.decodeFile(fullName)
                        binding.imgCard.setImageBitmap(decodedBitmap)
                        Log.d("YYYYYYYY","return decodedBitmap$decodedBitmap")
                        onInitIm(decodedBitmap.width.toFloat(), decodedBitmap.height.toFloat())
                    }else{
                        binding.imgCard.setImageBitmap(bitmap)
                        onInitIm(bitmap.width.toFloat(), bitmap.height.toFloat())
                    }
                }
                binding.imgFlash.setOnClickListener {
                    val selected = binding.imgFlash.isSelected
                    binding.imgFlash.isSelected = !selected
                    camera.cameraControl.enableTorch(!selected)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }, ContextCompat.getMainExecutor(this))
    }
    private fun onInitIm(imW: Float, imH: Float) {
        val screen = OpenConvert.getScreen(this)
        val newX = screen.x / 2f - imW / 2
        val newY = screen.y / 2f - imH / 2
        startMatrix.postTranslate(newX, newY)
        binding.imgCard.imageMatrix = startMatrix
    }
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouch(v: View?, event: MotionEvent): Boolean {
        when (event.action and MotionEvent.ACTION_MASK) {
            MotionEvent.ACTION_DOWN -> {
                startMatrix.set(binding.imgCard.imageMatrix)
                endMatrix.set(binding.imgCard.imageMatrix)
                startPointF.set(event.x, event.y)
                MODE = MODE_DRAG
            }
            MotionEvent.ACTION_POINTER_DOWN -> {
                startMatrix.set(endMatrix)
                distance = OpenConvert.getDistance(event)
                MODE = MODE_SCALE
            }
            MotionEvent.ACTION_MOVE -> {
                when (MODE) {
                    MODE_DRAG -> {
                        endMatrix.set(startMatrix)
                        endMatrix.postTranslate(
                            event.x - startPointF.x,
                            event.y - startPointF.y
                        )
                    }
                    MODE_SCALE -> {
                        scaleMultiple = OpenConvert.getDistance(event) / distance
                        endMatrix.set(startMatrix)
                        endMatrix.postScale(
                            scaleMultiple, scaleMultiple,
                            startPointF.x, startPointF.y
                        )
                    }
                }
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> {
                MODE = MODE_NONE
            }
        }
        binding.imgCard.imageMatrix = endMatrix
        return true
    }
}