package com.zxhy.hfilemanagermaster.filebrowse

import android.app.Dialog
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.example.hfilemanagermaster.R
import com.example.hfilemanagermaster.databinding.ActivityFileBrowseBinding
import com.zxhy.hfilemanagermaster.data.MediaDataC
import com.zxhy.hfilemanagermaster.dialog.showLoadingDialog
import com.zxhy.hfilemanagermaster.dialog.showOperationDialog
import com.zxhy.hfilemanagermaster.knife.apkFile
import com.zxhy.hfilemanagermaster.knife.audioFile
import com.zxhy.hfilemanagermaster.knife.deleteDirectory
import com.zxhy.hfilemanagermaster.knife.documentFile
import com.zxhy.hfilemanagermaster.knife.excelFile
import com.zxhy.hfilemanagermaster.knife.logFile
import com.zxhy.hfilemanagermaster.knife.pdfFile
import com.zxhy.hfilemanagermaster.knife.pptFile
import com.zxhy.hfilemanagermaster.knife.toast
import com.zxhy.hfilemanagermaster.knife.wordFile
import com.zxhy.hfilemanagermaster.knife.zipFile
import com.zxhy.hfilemanagermaster.permission.IntentLauncher
import com.zxhy.hfilemanagermaster.permission.PermissionLauncher
import com.zxhy.hfilemanagermaster.permission.alert
import com.zxhy.hfilemanagermaster.permission.requestStoreFollow
import com.zxhy.hfilemanagermaster.permission.storePermissionCheck
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class FileBrowseActivity : AppCompatActivity() {
    private lateinit var binding: ActivityFileBrowseBinding
    private var tittle = ""
    private lateinit var fileSelectAdapter: FileSelectorAdapter
    private lateinit var loadDialog: Dialog
    private lateinit var intentLauncher: IntentLauncher
    private lateinit var permissionLauncher: PermissionLauncher

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        intentLauncher = IntentLauncher(this)
        permissionLauncher = PermissionLauncher(this)
        binding = ActivityFileBrowseBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        tittle = intent.extras?.getString("tittle") ?: "tittle"
        binding.tvTittle.text = tittle

        window.statusBarColor = ContextCompat.getColor(this, R.color.color_C2F300)
        binding.ivArrow.setOnClickListener {
            finish()
        }

        fileSelectAdapter = FileSelectorAdapter()
        binding.rv.adapter = fileSelectAdapter

        binding.tvDelete.setOnClickListener {
            val list = fileSelectAdapter.getSelectFile()
            if (list.isEmpty()) return@setOnClickListener
            this.alert(
                "Currently selected ${list.size} items, are you sure to delete them",
                "Delete Confirm"
            ) {
                positiveButton("confirm") { dialog ->
                    deleteFiles(list)
                    dialog.dismiss()
                }
                negativeButton("cancel") { dialog ->
                    dialog.dismiss()
                }
                //禁止取消
                isCancel(false)
            }
        }
        binding.ivAll.setOnClickListener {
            it.isSelected = fileSelectAdapter.setToggleSelect()
        }



        if (storePermissionCheck()) {
            fileMode()
        } else {
            lockMode()
        }


    }

    private fun lockMode() {
        binding.clLock.visibility = View.VISIBLE
        binding.clShow.visibility = View.GONE
        binding.tvSet.setOnClickListener {
            this.requestStoreFollow(
                permissionLauncher,
                intentLauncher,
                disAgreeAction = {
                    lockMode()
                },
                agreeAction = {
                    fileMode()
                })
        }

    }

    private fun fileMode() {
        binding.clLock.visibility = View.GONE
        binding.clShow.visibility = View.VISIBLE

        loadDialog = showLoadingDialog()
        loadData()
    }

    private fun loadData() {

        when (tittle) {
            "Word" -> wordFile(this,
                onDoAction = { list ->
                    runOnUiThread {
                        loadDialog.dismiss()
                        fileSelectAdapter.addData(list)
                    }
                },
                finishAction = {
                    runOnUiThread {
                        loadDialog.dismiss()
                        isEmptyUi()
                    }
                })

            "Excel" -> excelFile(this,
                onDoAction = { list ->
                    runOnUiThread {
                        loadDialog.dismiss()
                        fileSelectAdapter.addData(list)
                    }
                },
                finishAction = {
                    runOnUiThread {
                        loadDialog.dismiss()
                        isEmptyUi()
                    }
                })

            "PDF" -> pdfFile(this,
                onDoAction = { list ->
                    runOnUiThread {
                        loadDialog.dismiss()
                        fileSelectAdapter.addData(list)
                    }
                },
                finishAction = {
                    runOnUiThread {
                        loadDialog.dismiss()
                        isEmptyUi()
                    }
                })

            "PPT" -> pptFile(this,
                onDoAction = { list ->
                    runOnUiThread {
                        loadDialog.dismiss()
                        fileSelectAdapter.addData(list)
                    }
                },
                finishAction = {
                    runOnUiThread {
                        loadDialog.dismiss()
                        isEmptyUi()
                    }
                })

            "Audio" -> audioFile(this,
                onDoAction = { list ->
                    runOnUiThread {
                        loadDialog.dismiss()
                        fileSelectAdapter.addData(list)
                    }
                },
                finishAction = {
                    runOnUiThread {
                        loadDialog.dismiss()
                        isEmptyUi()
                    }
                })

            "Apk" -> apkFile(this,
                onDoAction = { list ->
                    runOnUiThread {
                        loadDialog.dismiss()
                        fileSelectAdapter.addData(list)
                    }
                },
                finishAction = {
                    loadDialog.dismiss()
                    runOnUiThread { isEmptyUi() }
                })

            "Zip" -> zipFile(this,
                onDoAction = { list ->
                    runOnUiThread {
                        loadDialog.dismiss()
                        fileSelectAdapter.addData(list)
                    }
                },
                finishAction = {
                    loadDialog.dismiss()
                    runOnUiThread { isEmptyUi() }
                })

            "Log File" -> logFile(this,
                onDoAction = { list ->
                    runOnUiThread {
                        loadDialog.dismiss()
                        fileSelectAdapter.addData(list)
                    }
                },
                finishAction = {
                    loadDialog.dismiss()
                    runOnUiThread { isEmptyUi() }
                })

            "Document" -> documentFile(this,
                onDoAction = { list ->
                    runOnUiThread {
                        loadDialog.dismiss()
                        fileSelectAdapter.addData(list)
                    }
                },
                finishAction = {
                    loadDialog.dismiss()
                    runOnUiThread { isEmptyUi() }
                })
        }
    }

    private fun deleteFiles(files: List<MediaDataC>) = Thread {
        try {
            files.forEach {
                val file = File(it.path)
                if (file.exists()) {
                    if (file.isFile) file.delete() else deleteDirectory(file)
                }
            }
            lifecycleScope.launch(Dispatchers.Main) {
                val dialog = showOperationDialog(R.mipmap.dads_889562, "delete success!") {}
                delay(200)
                dialog.dismiss()
                fileSelectAdapter.removeData(files)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            runOnUiThread {
                toast("delete failed")
            }
        }
    }.start()

    private fun isEmptyUi() {

        val count = fileSelectAdapter.itemCount
        if (count == 0) {
            binding.rv.visibility = View.GONE
            binding.tvDelete.visibility = View.GONE
            binding.ivEmpty.visibility = View.VISIBLE
        } else {
            binding.rv.visibility = View.VISIBLE
            binding.tvDelete.visibility = View.VISIBLE
            binding.ivEmpty.visibility = View.GONE
        }

    }
}