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


import android.Manifest
import android.animation.Animator
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.Settings
import android.text.format.Formatter
import android.view.View
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.tools.R
import com.zxhyis.tools.base.TopActivity
import com.zxhyis.tools.databinding.ActivityLargeFilesBinding
import com.zxhyis.tools.logic.AudioBean
import com.zxhyis.tools.logic.Counts
import com.zxhyis.tools.logic.Logic
import com.zxhyis.tools.logic.setOnClick
import com.zxhyis.tools.logic.setStatusBarTextDark
import com.zxhyis.tools.logic.showToast
import com.zxhyis.tools.logic.startActivity
import com.zxhyis.tools.ui.adapter.LarageFileAdapter
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
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 LargeFilesActivity : TopActivity<ActivityLargeFilesBinding>() {

    private val largeList = ArrayList<AudioBean>()
    private val fileList = ArrayList<File>()
    private lateinit var fileAdapter: LarageFileAdapter
    private var allSize = 0L
    private var dialog: LoadingDialog? = null
    private val result =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {}
    private var needRefresh = false


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

    override fun init() {

        vb.inFile.tvTitle.text = getString(R.string.large_files)
        vb.inFile.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.inFile.imageSelectAll.setOnClick {
            fileList.clear()
            vb.inFile.imageSelectAll.isSelected = !vb.inFile.imageSelectAll.isSelected
            if (vb.inFile.imageSelectAll.isSelected) {
                fileAdapter.selectAll()
                for (audio in largeList) {
                    fileList.add(audio.file)
                }
                vb.btDelete.setBackgroundResource(R.drawable.bg_shape_set)
            } else {
                fileAdapter.deselectAll()
                for (audio in largeList) {
                    fileList.remove(audio.file)
                }
                vb.btDelete.setBackgroundResource(R.drawable.bg_shape_delete_no)
            }
        }

        vb.inFile.tvMenu.setOnClick {
            needRefresh = true
            if (largeList.size > 0) {
                vb.inFile.ivBack.visibility = View.GONE
                vb.inFile.tvMenu.visibility = View.GONE
                vb.inFile.imageSelectAll.visibility = View.VISIBLE
                vb.inFile.tvAll.visibility = View.VISIBLE
                vb.btDelete.visibility = View.VISIBLE
                vb.inFile.tvTitle.text = getString(R.string.select_large_file)
                fileAdapter.setShow()
            } else {
                getString(R.string.file_not_found).showToast()
            }
        }

        vb.btDelete.setOnClick {
            if (isCanDelete()) {
                CoroutineScope(Dispatchers.IO).launch {
                    delay(500)
                    deleteFiles()
                    launch(Dispatchers.Main) {
                        updateUI()
                    }
                }
            } else {
                "Please 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 "large_file")
                    finish()
                }
            }

            override fun onAnimationCancel(animation: Animator) {}

            override fun onAnimationRepeat(animation: Animator) {}

        })


    }

    private fun initAdapterAndRv() {
        CoroutineScope(Dispatchers.IO).launch {
            delay(500)

            val directory = File("/storage/emulated/0")
            if (directory.exists() && directory.isDirectory) {
                val files = directory.listFiles()
                if (files != null) {
                    for (file in files) {
                        if (file.exists() && file.isDirectory) {
                            for (app in file.absoluteFile.listFiles()!!) {
                                if (app.isFile && app.length() >= 10 * 1024 * 1024){
                                    largeList.add(
                                        AudioBean(
                                            app.absolutePath,
                                            app.name,
                                            Uri.parse(app.absolutePath),
                                            app,
                                            app.length(),
                                            apkTime = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                                app.absolutePath
                                            )
                                            else "",
                                            needRefresh
                                        )
                                    )
                                    allSize+=app.length()
                                }
                            }
                        }
                    }
                }
            }

//            val externalStorageDirectories = getExternalStorageDirectories()
//            for (directory in externalStorageDirectories) {
//                val files = directory.listFiles()
//                if (files != null) {
//                    for (file in files) {
//                        if (file.isFile && file.length() >= 10 * 1024 * 1024) {
//                            largeList.add(
//                                AudioBean(
//                                    file.absolutePath,
//                                    file.name,
//                                    Uri.parse(file.absolutePath),
//                                    file,
//                                    file.length(),
//                                    apkTime = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
//                                        file.absolutePath
//                                    )
//                                    else "",
//                                    needRefresh
//                                )
//                            )
//                            allSize+=file.length()
//                        }
//                    }
//                }
//            }

            fileAdapter = LarageFileAdapter(largeList, this@LargeFilesActivity, object : Logic {
                override fun doLogic() {
                    remove()
                    if (fileList.size > 0) {
                        vb.btDelete.setBackgroundResource(R.drawable.bg_shape_set)
                    } else {
                        vb.btDelete.setBackgroundResource(R.drawable.bg_shape_delete_no)
                    }
                }

            })

            launch(Dispatchers.Main) {
                if (largeList.size > 0) {
                    val linearLayoutManager = LinearLayoutManager(this@LargeFilesActivity)
                    linearLayoutManager.initialPrefetchItemCount = 10
                    vb.rvFile.apply {
                        layoutManager = linearLayoutManager
                        setHasFixedSize(true)
                        setItemViewCacheSize(20)
                        adapter = fileAdapter
                    }
                    vb.apply {
                        rvFile.visibility = View.VISIBLE
                        icNoFile.visibility = View.GONE
                        tvNoFile.visibility = View.GONE
                        totalSize.text = Formatter.formatFileSize(this@LargeFilesActivity, allSize)
                    }
                }else{
                    vb.apply {
                        rvFile.visibility = View.GONE
                        icNoFile.visibility = View.VISIBLE
                        tvNoFile.visibility = View.VISIBLE
                        totalSize.visibility = View.GONE
                    }
                }
                dialog?.dismiss()
            }
        }
    }

//    private fun getExternalStorageDirectories(): List<File> {
//        val directories = mutableListOf<File>()
//        directories.add(Environment.getExternalStorageDirectory())
//        return directories
//    }

    private fun updateUI() {
        vb.imageLoad.visibility = View.VISIBLE
        vb.tvLoad.visibility = View.VISIBLE
        vb.imageLoad.playAnimation()
        vb.rvFile.visibility = View.GONE
        vb.inFile.clInclude.visibility = View.GONE
        vb.btDelete.visibility = View.GONE
        vb.totalSize.visibility = View.GONE
    }

    @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 isCanDelete(): Boolean {
        return fileList.size > 0
    }

    private fun remove() {
        fileList.clear()
        for (audio in largeList) {
            if (audio.isSelected) {
                fileList.add(audio.file)
            } else {
                fileList.remove(audio.file)
            }
        }
    }

    private fun deleteFiles() {
        for (file in fileList) {
            file.delete()
        }
    }

    override fun onResume() {
        super.onResume()
        setStatusBarTextDark(this)
        allSize = 0
        largeList.clear()
        fileList.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
                    rvFile.visibility = View.VISIBLE
                    totalSize.visibility = View.VISIBLE
                    initAdapterAndRv()
                    dialog = LoadingDialog()
                    dialog?.isCancelable = false
                    dialog?.showNow(supportFragmentManager, "loading")
                }
            } else {
                vb.apply {
                    imagePer.visibility = View.VISIBLE
                    tvDes.visibility = View.VISIBLE
                    tvSet.visibility = View.VISIBLE
                    vb.tvSet.setBackgroundResource(R.drawable.bg_shape_set)
                    rvFile.visibility = View.GONE
                    totalSize.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)
                    rvFile.visibility = View.GONE
                    totalSize.visibility = View.GONE
                }
            } else {
                vb.apply {
                    imagePer.visibility = View.GONE
                    tvDes.visibility = View.GONE
                    tvSet.visibility = View.GONE
                    rvFile.visibility = View.VISIBLE
                    totalSize.visibility = View.VISIBLE
                    initAdapterAndRv()
                    dialog = LoadingDialog()
                    dialog?.isCancelable = false
                    dialog?.showNow(supportFragmentManager, "loading")
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        largeList.clear()
        fileList.clear()
    }

}