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.os.Build
import android.os.Environment
import android.provider.Settings
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.ActivityEmptyFileBinding
import com.zxhyis.tools.logic.Counts
import com.zxhyis.tools.logic.EmptyFileBean
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.logic.testLog
import com.zxhyis.tools.ui.adapter.EmptyAdapter
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

@SuppressLint("SimpleDateFormat")
class EmptyFileActivity : TopActivity<ActivityEmptyFileBinding>() {

    private val emptyList = ArrayList<EmptyFileBean>()
    private val fileList = ArrayList<String>()
    private lateinit var emptyAdapter: EmptyAdapter
    private var dialog: LoadingDialog? = null
    private val result =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {}
    private var needRefresh = false


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

    override fun init() {
        vb.inAudio.tvTitle.text = getString(R.string.empty_file)
        vb.inAudio.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.inAudio.imageSelectAll.setOnClick {
            fileList.clear()
            vb.inAudio.imageSelectAll.isSelected = !vb.inAudio.imageSelectAll.isSelected
            if (vb.inAudio.imageSelectAll.isSelected) {
                emptyAdapter.selectAll()
                for (file in emptyList) {
                    fileList.add(file.filePath)
                }
                vb.btDelete.setBackgroundResource(R.drawable.bg_shape_set)
            } else {
                emptyAdapter.deselectAll()
                for (file in emptyList) {
                    fileList.remove(file.filePath)
                }
                vb.btDelete.setBackgroundResource(R.drawable.bg_shape_delete_no)
            }
            testLog("${fileList.size}")
        }

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

        vb.btDelete.setOnClick {
            if (isCanDelete()) {
                CoroutineScope(Dispatchers.IO).launch {
                    delay(500)
                    for (dic in fileList) {
                        deleteFiles(File(dic))
                    }
                    launch(Dispatchers.Main) {
                        updateUI()
                    }
                }
            } else {
                "Please select at least one".showToast()
            }
        }

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

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

            override fun onAnimationCancel(animation: Animator) {}

            override fun onAnimationRepeat(animation: Animator) {}

        })


    }

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


            getEmptyFolders(Environment.getExternalStorageDirectory())


            emptyAdapter = EmptyAdapter(emptyList, this@EmptyFileActivity, 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 (emptyList.size > 0) {
                    val linearLayoutManager = LinearLayoutManager(this@EmptyFileActivity)
                    linearLayoutManager.initialPrefetchItemCount = 10
                    vb.rvAudio.apply {
                        layoutManager = linearLayoutManager
                        setHasFixedSize(true)
                        setItemViewCacheSize(20)
                        adapter = emptyAdapter
                    }
                    vb.apply {
                        rvAudio.visibility = View.VISIBLE
                        icNoFile.visibility = View.GONE
                        tvNoFile.visibility = View.GONE
                    }
                } else {
                    vb.apply {
                        rvAudio.visibility = View.GONE
                        icNoFile.visibility = View.VISIBLE
                        tvNoFile.visibility = View.VISIBLE
                    }
                }
                dialog?.dismiss()
            }

        }

    }

    private fun getEmptyFolders(file: File) {
        val files = file.listFiles()
        if (files != null) {
            for (subFile in files) {
                if (subFile.isDirectory) {
                    if (subFile.listFiles()?.isEmpty() == true) {
                        emptyList.add(
                            EmptyFileBean(
                                subFile.absolutePath,
                                subFile.name,
                                subFile,
                               0,
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                    subFile.absolutePath
                                ) else "",
                                needRefresh
                            )
                        )
                    } else {
                        getEmptyFolders(subFile)
                    }
                }
            }
        }
    }

    private fun updateUI() {
        vb.imageLoad.visibility = View.VISIBLE
        vb.tvLoad.visibility = View.VISIBLE
        vb.imageLoad.playAnimation()
        vb.rvAudio.visibility = View.GONE
        vb.inAudio.clInclude.visibility = View.GONE
        vb.btDelete.visibility = View.GONE
    }


    @RequiresApi(Build.VERSION_CODES.O)
    private 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 remove() {
        fileList.clear()
        for (fileParent in emptyList) {
            if (fileParent.isSelected) {
                fileList.add(fileParent.filePath)
            } else {
                fileList.remove(fileParent.filePath)
            }
        }
    }

    private fun isCanDelete(): Boolean {
        return fileList.size > 0
    }

    private fun deleteFiles(directory: File?) {
        directory?.deleteRecursively()
    }

    override fun onResume() {
        super.onResume()
        setStatusBarTextDark(this)
        emptyList.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
                    rvAudio.visibility = View.VISIBLE
                    initDatasource()
                    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)
                    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
                    initDatasource()
                    dialog = LoadingDialog()
                    dialog?.isCancelable = false
                    dialog?.showNow(supportFragmentManager, "loading")
                }
            }
        }
    }

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


}