package com.zxhyis.toolss.ui.page


import android.Manifest
import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.annotation.SuppressLint
import android.content.ContentResolver
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.toolss.R
import com.zxhyis.toolss.ad.AdmobUtils
import com.zxhyis.toolss.base.TopActivity
import com.zxhyis.toolss.databinding.ActivityVideoBinding
import com.zxhyis.toolss.logic.Counts
import com.zxhyis.toolss.logic.DialogDismissListener
import com.zxhyis.toolss.logic.Logic
import com.zxhyis.toolss.logic.VideoBean
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.logic.setStatusBarTextDark
import com.zxhyis.toolss.logic.shareMultipleVideos
import com.zxhyis.toolss.logic.showToast
import com.zxhyis.toolss.logic.startActivity
import com.zxhyis.toolss.logic.testLog
import com.zxhyis.toolss.ui.adapter.VideoAdapter
import com.zxhyis.toolss.ui.dialog.LoadingDialog
import com.zxhyis.toolss.ui.page.result.ResultActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class VideoActivity : TopActivity<ActivityVideoBinding>(),DialogDismissListener {

    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() {
        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()
                }
            }
        }
        vb.inPicture.tvTitle.text = getString(R.string.tv_video)

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

        vb.tvSet.setOnClick(javaClass.simpleName) {
            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(javaClass.simpleName) {
            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(javaClass.simpleName) {
            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(javaClass.simpleName) {
            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(javaClass.simpleName) {
            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?.setDismissListener(this)
        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()
                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
                    }
                }
                delay(1000)
                dialog?.dismiss()
            }
        }
    }

    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 filePath=getRealPathFromURI(contentResolver,file.videoUri)
            val file1=File(filePath)
            file1.delete()
            val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
            val uri = Uri.fromFile(file1)
            intent.data = uri
            sendBroadcast(intent)
        }
    }

    private fun getRealPathFromURI(contentResolver: ContentResolver, contentUri: Uri): String? {
        var cursor = contentResolver.query(contentUri, null, null, null, null)
        return if (cursor == null) {
            contentUri.path
        } else {
            cursor.moveToFirst()
            val index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
            val realPath = cursor.getString(index)
            cursor.close()
            realPath
        }
    }


    override fun onResume() {
        super.onResume()

    }

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

    override fun onDialogDismissed() {
        //MaxAdUtils.showMaxInterstitialAd(this,"interstitial_slot")
        AdmobUtils.showInterstitialAd(this)
    }


}