package com.zxhyis.tools.ui.`fun`


import android.Manifest
import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.zxhyis.tools.R
import com.zxhyis.tools.base.TopActivity
import com.zxhyis.tools.databinding.ActivityVideoBinding
import com.zxhyis.tools.logic.Counts
import com.zxhyis.tools.logic.ImageInfoBean
import com.zxhyis.tools.logic.Logic
import com.zxhyis.tools.logic.VideoBean
import com.zxhyis.tools.logic.setOnClick
import com.zxhyis.tools.logic.setStatusBarTextDark
import com.zxhyis.tools.logic.shareMultipleVideos
import com.zxhyis.tools.logic.showToast
import com.zxhyis.tools.logic.startActivity
import com.zxhyis.tools.logic.testLog
import com.zxhyis.tools.ui.adapter.ImageAdapter
import com.zxhyis.tools.ui.adapter.VideoAdapter
import com.zxhyis.tools.ui.dialog.LoadingDialog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class VideoActivity : TopActivity<ActivityVideoBinding>() {

    private val videoList = ArrayList<VideoBean>()
    private val videoSelectedList = ArrayList<VideoBean>()
    private lateinit var videoAdapter: VideoAdapter
    private val result =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {}
    private var dialog: LoadingDialog? = null
    private var needRefresh = false

    override fun getViewBinding1(): ActivityVideoBinding {
        return ActivityVideoBinding.inflate(layoutInflater)
    }

    override fun init() {
        vb.inPicture.tvTitle.text = getString(R.string.tv_video)

        vb.inPicture.ivBack.setOnClick {
            finish()
        }

        vb.tvSet.setOnClick {
            vb.tvSet.setBackgroundResource(R.drawable.bg_shape_set_click)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                result.launch(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION))
            } else {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    ), Counts.REQUEST_ALL_FILE
                )
            }
        }

        vb.inPicture.tvMenu.setOnClick {
            needRefresh=true
            if (videoList.size > 0) {
                vb.inPicture.ivBack.visibility = View.GONE
                vb.inPicture.tvMenu.visibility = View.GONE
                vb.inPicture.imageSelectAll.visibility = View.VISIBLE
                vb.inPicture.tvAll.visibility = View.VISIBLE
                vb.llBottom.visibility = View.VISIBLE
                vb.inPicture.tvTitle.text = getString(R.string.select_project)
                videoAdapter.setShow()
            } else {
                getString(R.string.file_not_found).showToast()
            }
        }

        vb.ivDelete.setOnClick {
            if (videoSelectedList.size>0){
                lifecycleScope.launch {
                    delay(500)
                    deleteVideos()
                    vb.apply {
                        inPicture.clInclude.visibility = View.GONE
                        rvVideo.visibility = View.GONE
                        icNoFile.visibility = View.GONE
                        tvNoFile.visibility = View.GONE
                        imageLoad.visibility = View.VISIBLE
                        llBottom.visibility=View.GONE
                        imageLoad.playAnimation()
                        tvLoad.visibility = View.VISIBLE
                    }
                }
            }else{
                "Select at least one".showToast()
            }
        }

        vb.imageLoad.addAnimatorListener(object :AnimatorListener{
            override fun onAnimationStart(animation: Animator) {

            }

            override fun onAnimationEnd(animation: Animator) {
                startActivity<ResultActivity>("from" to "video")
                finish()
            }

            override fun onAnimationCancel(animation: Animator) {
            }

            override fun onAnimationRepeat(animation: Animator) {
            }

        })

        vb.ivShare.setOnClick {
            when {
                videoSelectedList.size in 1..3 -> {
                    shareVideos()
                }

                videoSelectedList.size > 3 -> {
                    "Select up to three".showToast()
                }

                else -> {
                    "Select at least one".showToast()
                }
            }
        }

        vb.inPicture.imageSelectAll.setOnClick {
            videoSelectedList.clear()
            vb.inPicture.imageSelectAll.isSelected = !vb.inPicture.imageSelectAll.isSelected
            if (vb.inPicture.imageSelectAll.isSelected) {
                videoAdapter.selectAll()
                vb.ivShare.setImageResource(R.drawable.ic_share_selected)
                vb.ivDelete.setImageResource(R.drawable.ic_delete_selected)
            } else {
                videoAdapter.deselectAll()
                vb.ivShare.setImageResource(R.drawable.ic_share)
                vb.ivDelete.setImageResource(R.drawable.ic_delete)
            }
        }

        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                finish()
            }
        })

    }

    @SuppressLint("Recycle")
    private fun loadVideos(){
        dialog = LoadingDialog()
        dialog?.isCancelable = false
        dialog?.showNow(supportFragmentManager, "loading")

        CoroutineScope(Dispatchers.IO).launch {
            delay(1000)
            val projection = arrayOf(MediaStore.Video.Media._ID,MediaStore.Video.Media.DATA)
            val sortOrder = "${MediaStore.Video.Media.DATE_ADDED} DESC"
            val query = contentResolver.query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                projection,
                null,
                null,
                sortOrder
            )

            query?.use { cursor ->
                val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID)
                val name=cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA)
                while (cursor.moveToNext()) {
                    val id = cursor.getLong(idColumn)
                    val videoPath=cursor.getString(name)
                    val contentUri: Uri = Uri.withAppendedPath(
                        MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                        id.toString()
                    )
                    val file=File(videoPath)
                    videoList.add(VideoBean(videoPath,file,contentUri,needRefresh))
                    testLog("video:$videoPath")
                }
                cursor.close()
                dialog?.dismiss()


                videoAdapter = VideoAdapter(videoList,this@VideoActivity,object :Logic{
                    override fun doLogic() {
                        remove()
                        if (videoList.size > 0) {
                            vb.ivShare.setImageResource(R.drawable.ic_share_selected)
                            vb.ivDelete.setImageResource(R.drawable.ic_delete_selected)
                        } else {
                            vb.ivShare.setImageResource(R.drawable.ic_share)
                            vb.ivDelete.setImageResource(R.drawable.ic_delete)
                        }
                    }

                })
            }

            launch(Dispatchers.Main) {
                if (videoList.size>0){
                    val gridLayoutManager = GridLayoutManager(this@VideoActivity, 3)
                    gridLayoutManager.initialPrefetchItemCount = 10
                    vb.rvVideo.apply {
                        layoutManager = GridLayoutManager(this@VideoActivity, 3)
                        setHasFixedSize(true)
                        setItemViewCacheSize(20)
                        adapter = videoAdapter
                    }
                    vb.apply {
                        rvVideo.visibility = View.VISIBLE
                        icNoFile.visibility = View.GONE
                        tvNoFile.visibility = View.GONE
                    }
                }else{
                    vb.apply {
                        rvVideo.visibility = View.GONE
                        icNoFile.visibility = View.VISIBLE
                        tvNoFile.visibility = View.VISIBLE
                    }
                }
            }
        }
    }

    private fun remove(){
        videoSelectedList.clear()
        for (video in videoList){
            if (video.isSelected){
                videoSelectedList.add(video)
            }else{
                videoSelectedList.remove(video)
            }
        }
    }

    private fun shareVideos(){
        val uriList = ArrayList<Uri>()
        for (video in videoSelectedList) {
            uriList.add(video.videoUri)
        }
        shareMultipleVideos(uriList,this)
    }

    private fun deleteVideos(){
        for (file in videoSelectedList){
            val file1=File(file.videoPath)
            file1.delete()
        }
    }


    override fun onResume() {
        super.onResume()
        setStatusBarTextDark(this)
        videoList.clear()
        videoSelectedList.clear()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                vb.apply {
                    imagePer.visibility = View.GONE
                    tvDes.visibility = View.GONE
                    tvSet.visibility = View.GONE
                    rvVideo.visibility = View.VISIBLE
                    loadVideos()
                }
            } else {
                vb.apply {
                    imagePer.visibility = View.VISIBLE
                    tvDes.visibility = View.VISIBLE
                    tvSet.visibility = View.VISIBLE
                    vb.tvSet.setBackgroundResource(R.drawable.bg_shape_set)
                    rvVideo.visibility = View.GONE
                }
            }
        } else {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                vb.apply {
                    imagePer.visibility = View.VISIBLE
                    tvDes.visibility = View.VISIBLE
                    tvSet.visibility = View.VISIBLE
                    vb.tvSet.setBackgroundResource(R.drawable.bg_shape_set)
                    rvVideo.visibility = View.GONE
                }
            } else {
                vb.apply {
                    imagePer.visibility = View.GONE
                    tvDes.visibility = View.GONE
                    tvSet.visibility = View.GONE
                    rvVideo.visibility = View.VISIBLE
                    loadVideos()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (dialog!=null){
            dialog?.dismiss()
        }
        videoList.clear()
        videoSelectedList.clear()
        
    }



}