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

import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.ux.video.file.filerecovery.R
import com.ux.video.file.filerecovery.base.BaseActivity
import com.ux.video.file.filerecovery.databinding.ActivityDetailsBinding
import com.ux.video.file.filerecovery.db.ResultDataFiles
import com.ux.video.file.filerecovery.db.duration
import com.ux.video.file.filerecovery.db.resolution
import com.ux.video.file.filerecovery.db.targetFile
import com.ux.video.file.filerecovery.sort.RecoverOrDeleteManager
import com.ux.video.file.filerecovery.success.RecoverySuccessActivity
import com.ux.video.file.filerecovery.utils.Common
import com.ux.video.file.filerecovery.utils.ExtendFunctions.dpToPx
import com.ux.video.file.filerecovery.utils.FileType
import com.ux.video.file.filerecovery.utils.ScanType
import com.ux.video.file.filerecovery.video.PlayMediaManager
import com.ux.video.file.filerecovery.video.VideoPlayActivity
import java.io.File

class DetailsActivity : BaseActivity<ActivityDetailsBinding>() {

    companion object {
        val KEY_CLICK_ITEM = "click_item"
        val KEY_SHOW_SHARE = "show_share"
    }

    private   var playMediaManager: PlayMediaManager? = null

    private lateinit var fileType: FileType
    private var myData: ResultDataFiles? = null

    private var showShare = false

    override fun inflateBinding(inflater: LayoutInflater): ActivityDetailsBinding =
        ActivityDetailsBinding.inflate(inflater)

    override fun initView() {
        super.initView()
        myData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra(KEY_CLICK_ITEM, ResultDataFiles::class.java)
        } else {
            @Suppress("DEPRECATION")
            intent.getParcelableExtra(KEY_CLICK_ITEM)
        }
        val intExtra = intent.getIntExtra(Common.KEY_FILE_TYPE, FileType.PHOTO.value)

     myData?.fileType.let {
         if (it != null) {
             fileType = it
             Common.showLog("------fileType=${fileType}")
         }
     }
        showShare = intent.getBooleanExtra(KEY_SHOW_SHARE, false)
        setView()


    }

    override fun initData() {
        super.initData()
        binding.run {
            imageViewBack.setOnClickListener { finish() }
            myData?.let { resultPhotosFiles ->
                tvName.text = resultPhotosFiles.name
                tvPath.text = resultPhotosFiles.path
                tvSize.text = resultPhotosFiles.sizeString
                tvDate.text = Common.getFormatDate(resultPhotosFiles.lastModified)
                tvResolution.text = resultPhotosFiles.resolution()
                tvDuration.text = Common.formatDuration(resultPhotosFiles.duration())
                resultPhotosFiles.targetFile().let {
                    tvType.text = Common.getMimeTypeParts(it)
                }
            }
        }
    }

    private fun setView() {
        binding.run {
            layoutBottom.tvLeft.run {
                text = resources.getString(R.string.delete)
                setOnClickListener {
                    myData?.let { myData ->
                        RecoverOrDeleteManager.showConfirmDeleteDialog(
                            true,
                            supportFragmentManager,
                            lifecycleScope,
                            setOf(myData)
                        ) { count ->
                            complete(count, 1)
                        }
                    }
                }
            }

            layoutBottom.tvRight.run {
                myData?.let { myData ->
                    if (showShare) {
                        text = getString(R.string.share)
                        setOnClickListener {
                            Common.shareSingleFile(
                                this@DetailsActivity,
                                myData.targetFile(),
                                myData.fileType
                            )
                        }
                    } else {
                        text = getString(R.string.recover)
                        setOnClickListener {
                            RecoverOrDeleteManager.showRecoveringDialog(
                                supportFragmentManager,
                                lifecycleScope,
                                setOf(myData)
                            ) { count ->
                                complete(count, 0)
                            }
                        }
                    }
                }
            }

           myData?.let {

               when (it.fileType) {
                   FileType.PHOTO -> {
                       layoutName.isVisible = true
                       layoutPath.isVisible = true
                       layoutResolution.isVisible = true
                       layoutDate.isVisible = true
                       frameImage.setBackgroundResource(0)


                       layoutSeekbar.isVisible = false
                       layoutType.isVisible = false
                       layoutSize.isVisible = false
                       layoutDuration.isVisible = false

                       imPlay.isVisible = false

                       myData?.targetFile()?.let { loadImage(image, it) }
                   }

                   FileType.VIDEO -> {
                       layoutName.isVisible = true
                       layoutPath.isVisible = true
                       layoutResolution.isVisible = true
                       layoutDate.isVisible = true
                       layoutDuration.isVisible = true
                       frameImage.setBackgroundResource(0)


                       layoutSeekbar.isVisible = false
                       layoutType.isVisible = false
                       layoutSize.isVisible = false

                       imPlay.isVisible = true
                       myData?.let { data ->
                           loadImage(image, data.targetFile())
                           frameImage.setOnClickListener {
                               startActivity(
                                   Intent(
                                       this@DetailsActivity,
                                       VideoPlayActivity::class.java
                                   ).apply {
                                       putExtra(VideoPlayActivity.KEY_DATA, data)
                                   })
                           }
                       }
                   }

                   FileType.AUDIO -> {
                       Common.showLog("----------音频")
                       layoutName.isVisible = true
                       layoutPath.isVisible = true
                       layoutSize.isVisible = true
                       layoutDate.isVisible = true
                       layoutDuration.isVisible = true
                       layoutSeekbar.isVisible = true
                       imPlay.isVisible = true
                       frameImage.setBackgroundResource(R.drawable.bg_info_music_f2f2f7_8)

                       loadCenterImage(image, R.drawable.image_info_music)

                       initPlayAudio()
                       layoutResolution.isVisible = false
                       layoutType.isVisible = false
                   }

                   FileType.DOCUMENT -> {
                       layoutName.isVisible = true
                       layoutType.isVisible = true
                       layoutPath.isVisible = true
                       layoutSize.isVisible = true
                       layoutDate.isVisible = true

                       frameImage.setBackgroundResource(R.drawable.bg_info_music_f2f2f7_8)
                       myData?.targetFile()?.let {
                           loadCenterImage(image, Common.getFileIconRes(it))
                       }
                       imPlay.isVisible = false
                       layoutSeekbar.isVisible = false
                       layoutResolution.isVisible = false
                       layoutDuration.isVisible = false
                   }
               }
           }
        }
    }

    private fun loadCenterImage(image: ImageView, drawableId: Int) {
        image.setImageResource(drawableId)
        val params = image.layoutParams ?: ViewGroup.LayoutParams(
            180.dpToPx(this@DetailsActivity),
            180.dpToPx(this@DetailsActivity)
        )
        params.width = 180.dpToPx(this@DetailsActivity)
        params.height = 180.dpToPx(this@DetailsActivity)
        image.layoutParams = params
    }

    private fun loadImage(image: ImageView, file: File) {
        Glide.with(this@DetailsActivity)
            .load(file)
            .error(R.drawable.photo_place_holder)
            .apply(
                RequestOptions().transform(
                    CenterCrop(),
                    RoundedCorners(8.dpToPx(this@DetailsActivity))
                )
            )
            .listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable?>,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable,
                    model: Any,
                    target: Target<Drawable?>?,
                    dataSource: DataSource,
                    isFirstResource: Boolean
                ): Boolean {

                    return false
                }

            })
            .into(image)
    }


    private fun initPlayAudio() {
        myData?.targetFile()?.let {
            binding.run {
                playMediaManager = PlayMediaManager(
                    context = this@DetailsActivity, mediaFile = it,
                    seekBar = seekBar, playBtn = imPlay, onUpdateProgress = { current, total ->
                        textTimeCurrent.text = current
                        textTimeTotal.text = total
                    })

            }
        }
    }


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

    override fun onDestroy() {
        super.onDestroy()
        playMediaManager?.stopPlayAudio()
    }
}