package com.audio.record.screen.test.activity


import android.graphics.RectF
import android.net.Uri
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackParameters
import androidx.media3.exoplayer.ExoPlayer
import androidx.navigation.fragment.NavHostFragment
import com.audio.record.screen.test.App
import com.audio.record.screen.test.R
import com.audio.record.screen.test.base.BaseActivity
import com.audio.record.screen.test.databinding.ActivityPreviewBinding
import com.audio.record.screen.test.tool.Common
import com.audio.record.screen.test.tool.FFmpegKitTool
import com.audio.record.screen.test.viewmodel.PreviewViewModel
import java.io.File
import kotlin.properties.Delegates


class PreviewActivity : BaseActivity<ActivityPreviewBinding>(), View.OnClickListener {

    private lateinit var exoPlayer: ExoPlayer

    //将当前需要处理的原视频复制到内部存储，方便操作
    private lateinit var copyFile: File

    private var copyResult by Delegates.notNull<Boolean>()
    private lateinit var viewModel: PreviewViewModel
    override fun initBinding(): ActivityPreviewBinding =
        ActivityPreviewBinding.inflate(layoutInflater)


    override fun getFullColor(): Boolean = true
    override fun onInitPadding(): Boolean  = true
    override fun onCreateInit() {
        initPlay()
        viewModel = ViewModelProvider(this)[PreviewViewModel::class.java]
        binding.imPlay.setOnClickListener {
            if (!binding.imPlay.isSelected) {
                exoPlayer.play()
            } else {
                exoPlayer.pause()
            }
            binding.imPlay.isSelected = !binding.imPlay.isSelected
        }

        val thumbDir = File(App.instanceApp.cacheDir, "thumb").apply {
            if (!exists()) {
                mkdir()
            } else {
                Common.deleteAllFilesInDirectory(this.absolutePath)
            }
        }
//        val thumbAdapter = ThumbAdapter(this@PreviewActivity)
//        binding.thumbRecycler.apply {
//            layoutManager =
//                LinearLayoutManager(this@PreviewActivity, RecyclerView.HORIZONTAL, false)
//            adapter = thumbAdapter
//        }
        val open = App.instanceApp.assets.open("record_1748398994963.mp4")
        copyFile = File(App.instanceApp.cacheDir, "temp_video.mp4")
        //原视频复制到内部存储
        FFmpegKitTool.copy(copyFile, open, thumbDir.absolutePath) {
            Common.showLog("--------copy success")
            copyResult = it
        }


        initListener()
        viewModel.cropRatioText.observe(this) {
            if (it.equals("原始")) {
                val videoRatio = Common.getVideoRatio(copyFile.absolutePath)
                binding.cropView.setAspectRatio(videoRatio)
            } else {
                val split = it.split(":")
                binding.cropView.setAspectRatio(split[0].toFloat() / split[1].toFloat())
            }
        }
        viewModel.saveCrop.observe(this){

            val cropFile = File(App.instanceApp.cacheDir, "crop_video_${System.currentTimeMillis()}.mp4")
            val videoWH = Common.getVideoWH(copyFile.absolutePath)

            val rawCropRect = binding.cropView.getCropRectInVideoCoords(videoWH.first ,
                videoWH.second
            )

            val x = rawCropRect?.left?.toInt() ?: 0
            val y = rawCropRect?.top?.toInt() ?: 0
            val w = rawCropRect?.width()?.toInt() ?: 0
            val h = rawCropRect?.height()?.toInt() ?: 0

            Common.showLog("-------videoWH  w=${videoWH.first}  h=${videoWH.second} x=${x} y = $y w= $w h= $h")
            FFmpegKitTool.cropVideo(copyFile.absolutePath,cropFile.absolutePath,x,y,w,h)


        }
        viewModel.changeSpeed.observe(this){
            exoPlayer.playbackParameters = PlaybackParameters(it, it)
        }

    }

    private fun initListener() {
        val navHostFragment = supportFragmentManager
            .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController
        navController.addOnDestinationChangedListener { controller, destination, arguments ->
            Common.showLog("NavControllerListener 当前的目的地: id=${destination.id} name=${destination.displayName}  label=${destination.label}")
            binding.cropView.isVisible = false
            when (destination.id) {
                R.id.fragmentCut -> {
                    viewModel.updateCopyResult(Pair(copyResult, copyFile.absolutePath))
                    Common.showLog("----fragmentCut")
                }

                R.id.fragmentCropping -> {
                    Common.showLog("----fragmentCropping")
                    initCropView()

                }

                R.id.fragmentVolume -> {
                    Common.showLog("----fragmentVolume")
                    viewModel.updateCopyResult(Pair(copyResult, copyFile.absolutePath))
                }

                R.id.fragmentSpeed -> {
                    Common.showLog("----fragmentSpeed")
                    viewModel.updateCopyResult(Pair(copyResult, copyFile.absolutePath))
                }
            }
        }
    }


    private fun initCropView() {
        binding.cropView.isVisible = true
        // 延迟执行以确保布局完成
        binding.playerView.post {
            val contentFrame: View =
                binding.playerView.findViewById(androidx.media3.ui.R.id.exo_content_frame)
            if (contentFrame != null) {
                // 获取在 cropView 坐标系中的显示区域
                val videoRect = RectF()
                val contentLoc = IntArray(2)
                val cropLoc = IntArray(2)
                contentFrame.getLocationOnScreen(contentLoc)
                binding.cropView.getLocationOnScreen(cropLoc)
                val offsetX = (contentLoc[0] - cropLoc[0]).toFloat()
                val offsetY = (contentLoc[1] - cropLoc[1]).toFloat()
                videoRect.left = offsetX
                videoRect.top = offsetY
                videoRect.right = offsetX + contentFrame.width
                videoRect.bottom = offsetY + contentFrame.height
                // 设置裁剪区域限制边界
                binding.cropView.setVideoDisplayBounds(videoRect)
            }
        }
    }


    private fun initPlay() {
        val uri = Uri.parse("asset:///record_1748398994963.mp4")
        exoPlayer = ExoPlayer.Builder(this).build()

        binding.playerView.player = exoPlayer
        val mediaItem = MediaItem.fromUri(uri)
        exoPlayer.setMediaItem(mediaItem)
        exoPlayer.prepare()
//        exoPlayer.playWhenReady = true
    }

    override fun onClick(p0: View?) {

    }


}