package com.ux.video.file.filerecovery.video

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import androidx.lifecycle.lifecycleScope
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import com.ux.video.file.filerecovery.R
import com.ux.video.file.filerecovery.base.BaseActivity
import com.ux.video.file.filerecovery.databinding.ActivityVideoPlayBinding
import com.ux.video.file.filerecovery.sort.RecoverOrDeleteManager
import com.ux.video.file.filerecovery.db.ResultDataFiles
import com.ux.video.file.filerecovery.db.targetFile
import com.ux.video.file.filerecovery.success.RecoverySuccessActivity
import com.ux.video.file.filerecovery.utils.Common
import com.ux.video.file.filerecovery.utils.FileType

class VideoPlayActivity : BaseActivity<ActivityVideoPlayBinding>() {

    companion object {
        val KEY_DATA = "key_data"
    }

    private lateinit var player: ExoPlayer
    private var myData: ResultDataFiles? = null
    private val updateHandler = Handler(Looper.getMainLooper())
    override fun inflateBinding(inflater: LayoutInflater): ActivityVideoPlayBinding =
        ActivityVideoPlayBinding.inflate(inflater)

    override fun initView() {
        super.initView()
    }

    override fun addPadding(): Boolean = false

    override fun initData() {
        super.initData()
        myData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra(KEY_DATA, ResultDataFiles::class.java)
        } else {
            @Suppress("DEPRECATION")
            intent.getParcelableExtra(KEY_DATA)
        }
//        initPlayer()
        binding.run {
            myData?.let { resultPhotosFiles->
                imageBack.setOnClickListener { finish() }
                resultPhotosFiles.targetFile().let {
                    PlayMediaManager(context = this@VideoPlayActivity, mediaFile = it, playView = playerView,
                        seekBar = seekBar, playBtn = playImage, onUpdateProgress = { current,total->
                            textTimeCurrent.text = current
                            textTimeTotal.text = total
                        } )
                }

//                playImage.setOnClickListener {
//                    if (player.playbackState == Player.STATE_ENDED) {
//                        player.seekTo(0)
//                    }
//                    if (!player.isPlaying) {
//                        player.play()
//                        it.isSelected = true
//                    } else {
//                        player.pause()
//                        it.isSelected = false
//                    }
//                }
//                seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
//                    override fun onProgressChanged(
//                        seekBar: SeekBar?,
//                        progress: Int,
//                        fromUser: Boolean
//                    ) {
//                        if (fromUser) {
//                            val newPosition = progress * player.duration / 100
//                            player.seekTo(newPosition)
//                        }
//                    }
//
//                    override fun onStartTrackingTouch(seekBar: SeekBar?) {
//
//                    }
//
//                    override fun onStopTrackingTouch(seekBar: SeekBar?) {
//
//                    }
//
//                })
//                startProgressUpdater()
                layoutBottom.tvLeft.run {
                    text = resources.getString(R.string.delete)
                    setOnClickListener {
                        RecoverOrDeleteManager.showConfirmDeleteDialog(
                            true,
                            supportFragmentManager,
                            lifecycleScope,
                            setOf(resultPhotosFiles)
                        ) { count ->
                            complete(count, 1)
                        }
                    }
                }

                layoutBottom.tvRight.run {
                    text = resources.getString(R.string.recover)
                    setOnClickListener {
                        RecoverOrDeleteManager.showRecoveringDialog(
                            supportFragmentManager,
                            lifecycleScope,
                            setOf(resultPhotosFiles)
                        ) { count ->
                            complete(count, 0)
                        }
                    }
                }
            }
        }
    }

    private fun startProgressUpdater() {
        updateHandler.post(object : Runnable {
            override fun run() {
                if (player.isPlaying || player.isLoading) {
                    val pos = player.currentPosition
                    val dur = player.duration.takeIf { it > 0 } ?: 1L
                    val progress = (pos * 100 / dur).toInt()
                    binding.seekBar.progress = progress

                    binding.textTimeCurrent.text = Common.formatDuration(pos)
                    binding.textTimeTotal.text = Common.formatDuration(dur)
                }
                updateHandler.postDelayed(this, 500)
            }
        })
    }

    private fun initPlayer() {
        myData?.let {
            player = ExoPlayer.Builder(this).build()
            binding.playerView.player = player
            val mediaItem = MediaItem.fromUri(Uri.fromFile(it.targetFile()))
            player.addListener(object : Player.Listener {
                override fun onPlaybackStateChanged(playbackState: Int) {
                    super.onPlaybackStateChanged(playbackState)
                    when (playbackState) {
                        Player.STATE_IDLE -> {

                        }

                        Player.STATE_BUFFERING -> {

                        }

                        Player.STATE_READY -> {

                        }

                        Player.STATE_ENDED -> {
                            binding.playImage.isSelected = false
                        }
                    }

                }
            })
            player.setMediaItem(mediaItem)
            player.prepare()
        }

    }


    private fun complete(number: Int, type: Int) {
        finish()
        startActivity(Intent(this@VideoPlayActivity, RecoverySuccessActivity::class.java).apply {
            putExtra(RecoverySuccessActivity.KEY_SUCCESS_COUNT, number)
            putExtra(RecoverySuccessActivity.KEY_SUCCESS_TYPE, type)
            putExtra(Common.KEY_FILE_TYPE, FileType.VIDEO.value)
        })
    }
}