package com.zxhyis.toolss.ui.page


import android.Manifest
import android.animation.Animator
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.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.zxhyis.toolss.R
import com.zxhyis.toolss.ad.AdmobUtils

import com.zxhyis.toolss.base.TopActivity
import com.zxhyis.toolss.databinding.ActivityRecentlyBinding
import com.zxhyis.toolss.logic.Counts
import com.zxhyis.toolss.logic.DialogDismissListener
import com.zxhyis.toolss.logic.ImageAndVideoBean
import com.zxhyis.toolss.logic.Logic
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.logic.setStatusBarTextDark
import com.zxhyis.toolss.logic.shareMultipleImagesAndVideos
import com.zxhyis.toolss.logic.showToast
import com.zxhyis.toolss.logic.startActivity
import com.zxhyis.toolss.ui.adapter.RecentAdapter
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
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.BasicFileAttributes
import java.sql.Date
import java.text.SimpleDateFormat

class RecentlyActivity : TopActivity<ActivityRecentlyBinding>(),DialogDismissListener {

    private lateinit var recentAdapter: RecentAdapter
    private val dataList = ArrayList<ImageAndVideoBean>()
    private val selectedList = ArrayList<ImageAndVideoBean>()
    private val fileList = ArrayList<File>()
    private val result =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {}
    private var dialog: LoadingDialog? = null
    private var needRefresh = false


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

    @SuppressLint("SetTextI18n")
    override fun init() {
        setStatusBarTextDark(this)
        dataList.clear()
        selectedList.clear()
        fileList.clear()
        vb.tvSet.setBackgroundResource(R.drawable.bg_shape_set)
        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
                    rvAudio.visibility = View.VISIBLE
                    loadImagesAndVideo()
                }
            } else {
                vb.apply {
                    imagePer.visibility = View.VISIBLE
                    tvDes.visibility = View.VISIBLE
                    tvSet.visibility = View.VISIBLE
                    vb.tvSet.setBackgroundResource(R.drawable.bg_shape_set)
                    rvAudio.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)
                    rvAudio.visibility = View.GONE
                }
            } else {
                vb.apply {
                    imagePer.visibility = View.GONE
                    tvDes.visibility = View.GONE
                    tvSet.visibility = View.GONE
                    rvAudio.visibility = View.VISIBLE
                    loadImagesAndVideo()
                }
            }
        }
        vb.tvSet.setOnClick(javaClass.simpleName) {

            vb.inRecent.tvTitle.text = "Recent Files"
            vb.inRecent.ivBack.setOnClick(javaClass.simpleName) {
                finish()
            }

            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.inRecent.tvMenu.setOnClick(javaClass.simpleName) {
            needRefresh = true
            if (dataList.size > 0) {
                vb.inRecent.ivBack.visibility = View.GONE
                vb.inRecent.tvMenu.visibility = View.GONE
                vb.inRecent.imageSelectAll.visibility = View.VISIBLE
                vb.inRecent.tvAll.visibility = View.VISIBLE
                vb.llBottom.visibility = View.VISIBLE
                vb.inRecent.tvTitle.text = getString(R.string.select_project)
                recentAdapter.setShow()
            } else {
                getString(R.string.file_not_found).showToast()
            }
        }


        vb.inRecent.imageSelectAll.setOnClick(javaClass.simpleName) {
            fileList.clear()
            selectedList.clear()
            vb.inRecent.imageSelectAll.isSelected = !vb.inRecent.imageSelectAll.isSelected
            if (vb.inRecent.imageSelectAll.isSelected) {
                for (data in dataList) {
                    fileList.add(data.file)
                    selectedList.add(
                        ImageAndVideoBean(
                            data.path,
                            data.file,
                            data.type,
                            data.fileName,
                            data.fileSize,
                            data.recentTime,
                            data.imageUri,
                            data.videoUri
                        )
                    )
                }
                recentAdapter.selectAll()
                vb.ivShare.setImageResource(R.drawable.ic_share_selected)
                vb.ivDelete.setImageResource(R.drawable.ic_delete_selected)
            } else {
                for (data in dataList) {
                    fileList.remove(data.file)
                    selectedList.remove(
                        ImageAndVideoBean(
                            data.path,
                            data.file,
                            data.type,
                            data.fileName,
                            data.fileSize,
                            data.recentTime,
                            data.imageUri,
                            data.videoUri
                        )
                    )
                }
                recentAdapter.deselectAll()
                vb.ivShare.setImageResource(R.drawable.ic_share)
                vb.ivDelete.setImageResource(R.drawable.ic_delete)
            }
        }

        vb.ivShare.setOnClick(javaClass.simpleName) {
            when {
                fileList.size in 1..3 -> {
                    share()
                }

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

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

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

            override fun onAnimationEnd(animation: Animator) {
                lifecycleScope.launch {
                    delay(500)
                    startActivity<ResultActivity>("from" to "recent")
                    finish()
                }
            }

            override fun onAnimationCancel(animation: Animator) {}

            override fun onAnimationRepeat(animation: Animator) {}

        })

        vb.ivDelete.setOnClick(javaClass.simpleName) {
            if (fileList.size > 0) {
                CoroutineScope(Dispatchers.IO).launch {
                    delay(500)
                    delete()
                    launch(Dispatchers.Main) {
                        vb.apply {
                            inRecent.clInclude.visibility = View.GONE
                            rvAudio.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()
            }
        }

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


    }

    override fun onResume() {
        super.onResume()

    }

    private fun loadImagesAndVideo() {
        dialog = LoadingDialog()
        dialog?.setDismissListener(this)
        dialog?.isCancelable = false
        dialog?.showNow(supportFragmentManager, "loading")

        CoroutineScope(Dispatchers.IO).launch {


            val contentResolver = contentResolver
            val imagesUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            val videosUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
            val projection =
                arrayOf(MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DATE_ADDED)
            val sortOrder = "${MediaStore.MediaColumns.DATE_ADDED} DESC"
            val cursorImages = contentResolver.query(imagesUri, projection, null, null, sortOrder)
            val cursorVideos = contentResolver.query(videosUri, projection, null, null, sortOrder)

            cursorImages?.use { cursor ->
                val columnIndexData = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
                while (cursor.moveToNext()) {
                    val imagePath = cursor.getString(columnIndexData)
                    val file = File(imagePath)
                    dataList.add(
                        ImageAndVideoBean(
                            path = imagePath,
                            file = file,
                            type = 1,
                            fileName = file.name,
                            fileSize = file.length(),
                            recentTime = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                file.absolutePath
                            ) else "",
                            imageUri = Uri.parse(imagePath),
                            isShow = needRefresh
                        )
                    )
                }
            }

            cursorVideos?.use { cursor ->
                val columnIndexData = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
                while (cursor.moveToNext()) {
                    val videoPath = cursor.getString(columnIndexData)
                    val file = File(videoPath)
                    dataList.add(
                        ImageAndVideoBean(
                            path = videoPath,
                            file = file,
                            type = 2,
                            fileName = file.name,
                            fileSize = file.length(),
                            recentTime = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                file.absolutePath
                            ) else "",
                            imageUri = Uri.parse(videoPath),
                            isShow = needRefresh
                        )
                    )
                }
            }
            cursorImages?.close()
            cursorVideos?.close()
            recentAdapter = RecentAdapter(dataList, this@RecentlyActivity, object : Logic {
                override fun doLogic() {
                    remove()
                    if (fileList.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 (dataList.size > 0) {
                    val linearLayoutManager = LinearLayoutManager(
                        this@RecentlyActivity
                    )
                    linearLayoutManager.initialPrefetchItemCount = 3
                    vb.rvAudio.apply {
                        layoutManager = linearLayoutManager
                        setHasFixedSize(true)
                        setItemViewCacheSize(20)
                        adapter = recentAdapter
                    }
                    vb.tvNoFile.visibility = View.GONE
                    vb.rvAudio.visibility = View.VISIBLE
                    vb.icNoFile.visibility = View.GONE
                } else {
                    vb.tvNoFile.visibility = View.VISIBLE
                    vb.rvAudio.visibility = View.GONE
                    vb.icNoFile.visibility = View.VISIBLE
                }
                delay(1000)
                dialog?.dismiss()
            }

        }


    }

    private fun delete() {
        for (data in selectedList) {
            val filePath=getRealPathFromURI(contentResolver,data.imageUri!!)
            val file=File(filePath)
            file.delete()
            val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
            val uri = Uri.fromFile(file)
            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
        }
    }

    private fun remove() {
        fileList.clear()
        for (data in dataList) {
            if (data.isSelected) {
                fileList.add(data.file)
                selectedList.add(
                    ImageAndVideoBean(
                        data.path,
                        data.file,
                        data.type,
                        data.fileName,
                        data.fileSize,
                        data.recentTime,
                        data.imageUri,
                        data.videoUri
                    )
                )
            } else {
                fileList.remove(data.file)
                selectedList.remove(
                    ImageAndVideoBean(
                        data.path,
                        data.file,
                        data.type,
                        data.fileName,
                        data.fileSize,
                        data.recentTime,
                        data.imageUri,
                        data.videoUri
                    )
                )
            }
        }
    }

    @SuppressLint("SimpleDateFormat")
    @RequiresApi(Build.VERSION_CODES.O)
    fun getFileCreationTime(filePath: String): String? {
        try {
            val path = Paths.get(filePath)
            val attr = Files.readAttributes(path, BasicFileAttributes::class.java)
            val creationTime = attr.creationTime()
            val date = Date(creationTime.toMillis())
            val format = SimpleDateFormat("yyyy-MM-dd HH:mm")
            return format.format(date)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    private fun share() {
        val uriList = ArrayList<Uri>()
        for (image in selectedList) {
            if (image.type == 1) {
                uriList.add(image.imageUri!!)
            }else{
                uriList.add(image.videoUri!!)
            }
        }
        shareMultipleImagesAndVideos(uriList, this)
    }


    override fun onDestroy() {
        super.onDestroy()
        dataList.clear()
        fileList.clear()
        selectedList.clear()
        if (dialog != null) {
            dialog?.dismiss()
        }
    }

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

}