package com.apps.sketchmaster.view

import com.apps.sketchmaster.data.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.ad.maxlibrary.MaxManager
import com.apps.sketchmaster.utils.AllUtils
import com.google.common.util.concurrent.ListenableFuture
import com.apps.sketchmaster.databinding.ActivityStartSketchBinding
import com.apps.sketchmaster.view.ShowTitleActivity

class SketchStartActivity : AppCompatActivity(), View.OnTouchListener {
    private lateinit var binding: ActivityStartSketchBinding
    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 = ActivityStartSketchBinding.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.setting.isSelected = false
        binding.llBottom.visibility = View.GONE
        binding.setting.setOnClickListener { v ->
                val selected = v.isSelected
                if (selected) {
                    binding.setting.isSelected = false
                    binding.llBottom.visibility = View.GONE
                } else {
                    binding.setting.isSelected = true
                    binding.llBottom.visibility = View.VISIBLE
                }
        }
        requestPermissionLauncher =
            registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
                if (granted) {
                    startCamera()
                } else {
                    Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
                }
            }
        init()
        MaxManager.onLoadAd()
        MaxManager.startShowMaxAd (this@SketchStartActivity){  }
    }

    private fun init() {
        fullName = intent.getStringExtra(PATH_KEY) ?: ""
        Log.d("YYYYYY", fullName + "")
        binding.back.setOnClickListener { finish() }
        mainViewModel.isBase.observe(this) { isLike ->
            binding.imgLike.isSelected = isLike
        }
        mainViewModel.checkIsBase(fullName)
        binding.imgLike.setOnClickListener { v ->
            val selected = v.isSelected
            binding.imgLike.isSelected = !selected
            if (!selected) {
                mainViewModel.addBase(fullName)
            } else {
                mainViewModel.deleteBasePath(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 = AllUtils.switchTypeFromAssets(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 = AllUtils.returnPoint(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 = AllUtils.calculateDistance(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 = AllUtils.calculateDistance(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
    }
}