package com.audio.record.screen.test.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.audio.record.screen.test.App
import com.audio.record.screen.test.adapter.ThumbAdapter
import com.audio.record.screen.test.base.BaseFragment
import com.audio.record.screen.test.databinding.FragmentCutBinding
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 com.jaygoo.widget.OnRangeChangedListener
import com.jaygoo.widget.RangeSeekBar
import java.io.File
import kotlin.properties.Delegates

class CutFragment : BaseFragment<FragmentCutBinding>() ,View.OnClickListener{
    //毫秒单位
    private var leftV by Delegates.notNull<Float>()
    private lateinit var viewModel: PreviewViewModel
    private var rightV by Delegates.notNull<Float>()
    private var param1: String? = null
    private var param2: String? = null
    private lateinit var copyFilePath: String
    private lateinit var navController:NavController
    companion object {

        @JvmStatic
        fun newInstance() =
            CutFragment().apply {
                arguments = Bundle().apply {
//                    putString(ARG_PARAM1, param1)
//                    putString(ARG_PARAM2, param2)
                }
            }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
//            param1 = it.getString(ARG_PARAM1)
//            param2 = it.getString(ARG_PARAM2)
        }
    }


    override fun initBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentCutBinding =
        FragmentCutBinding.inflate(inflater, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
           navController = findNavController()
        viewModel = ViewModelProvider(requireActivity())[PreviewViewModel::class.java]
        initThumb()
        initClick()
    }


    private fun initThumb(){
        val thumbDir = File(App.instanceApp.cacheDir, "thumb")
        val thumbAdapter = ThumbAdapter(requireContext())
        binding.thumbRecycler.apply {
            layoutManager =
                LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
            adapter = thumbAdapter
        }
//        val open = App.instanceApp.assets.open("temp_video.mp4")
//        tempFile = File(App.instanceApp.cacheDir, "temp_video.mp4")
        viewModel.copySuccess.observe(requireActivity()){
            if (it.first) {
                Common.showLog("-------11111111111111")
                copyFilePath = it.second
                val allImagePaths = Common.getNaturallySortedThumbFiles(thumbDir.absolutePath)
                thumbAdapter.updateData(allImagePaths)
                initSeekBar()
            }
        }

    }
    private fun initClick() {
        binding.imClose.setOnClickListener(this)
        binding.imSave.setOnClickListener(this)
    }
    private fun initSeekBar() {
        val durationMs = Common.getVideoDurationMs(copyFilePath)

//        val millisToSeconds = Common.millisToSeconds(durationMs)
        Common.showLog("----durationMs=${durationMs}  ")
        binding.rangeSlider.run {
            durationMs.toFloat().let {
                setRange(0f, it)
                leftSeekBar?.setIndicatorText(Common.formatSeconds(0f))
                rightSeekBar?.setIndicatorText(Common.formatSeconds(it))
                setProgress(0f, it)

            }


            setOnRangeChangedListener(object : OnRangeChangedListener {
                override fun onRangeChanged(
                    view: RangeSeekBar?,
                    leftValue: Float,
                    rightValue: Float,
                    isFromUser: Boolean
                ) {
                    view?.leftSeekBar?.setIndicatorText(Common.formatSeconds(leftValue))
                    view?.rightSeekBar?.setIndicatorText(Common.formatSeconds(rightValue))
                    leftV = leftValue
                    rightV = rightValue

                }

                override fun onStartTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {

                }

                override fun onStopTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {

                }

            })
        }
    }

    override fun onClick(p0: View?) {
        p0?.let {
            if (it == binding.imSave) {
                trimVideoFile()
            }else if(it == binding.imClose){
                navController.navigateUp()
            }
        }
    }
    fun trimVideoFile() {
        val resultFile = File(requireContext().cacheDir, "test_${System.currentTimeMillis()}.mp4")
        val left = leftV.toString()
        val right = rightV.toString()
        Common.showLog("------left=${left}  right=${right}")
//        FFmpegKitTool.trimVideo(tempFile.absolutePath, resultFile.absolutePath, left, right)
        FFmpegKitTool.cropVideoWithFFmpeg(copyFilePath, resultFile.absolutePath,leftV,rightV)
    }
}