package com.zxhy.hfilemanagermaster.duplicate

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.ActivityDupPictureBinding
import com.zxhy.hfilemanagermaster.data.DupImageData
import com.zxhy.hfilemanagermaster.dialog.showLoadingDialog
import com.zxhy.hfilemanagermaster.dialog.showOperationDialog
import com.zxhy.hfilemanagermaster.knife.deleteDirectory
import com.zxhy.hfilemanagermaster.knife.dupImageMedia
import com.zxhy.hfilemanagermaster.knife.dupImageStore
import com.zxhy.hfilemanagermaster.knife.getDupImageList
import com.zxhy.hfilemanagermaster.knife.toast
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 DupPictureActivity : AppCompatActivity() {
    private lateinit var binding: ActivityDupPictureBinding
    private lateinit var adapter: DupImageAdapter
    private lateinit var dialog: 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 = ActivityDupPictureBinding.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
        }
        window.statusBarColor = ContextCompat.getColor(this, R.color.color_C2F300)
        binding.ivArrow.setOnClickListener {
            finish()
        }
        adapter = DupImageAdapter {
            binding.ivAll.isSelected = it
        }
        binding.rv.adapter = adapter
        binding.ivAll.setOnClickListener {
            it.isSelected = adapter.setToggleSelect()
        }
        binding.tvDelete.setOnClickListener {
            val num = adapter.getSelectNum()
            if (num == 0) return@setOnClickListener
            this.alert(
                "Currently selected $num items, are you sure to delete them",
                "Delete Confirm"
            ) {
                positiveButton("sure") { dialog ->
                    val data = adapter.getSelectData().map { File(it.path) }
                    deleteFiles(data)
                    dialog.dismiss()
                }
                negativeButton("cancel") { dialog ->
                    dialog.dismiss()
                }
                //禁止取消
                isCancel(false)
            }
        }

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

    private fun lockMode() {
        binding.clLock.visibility = View.VISIBLE
        binding.rv.visibility = View.INVISIBLE
        binding.ivAll.visibility = View.GONE
        binding.tvAll.visibility = View.GONE
        binding.tvDelete.visibility = View.GONE

        binding.tvSet.setOnClickListener {
            this.requestStoreFollow(
                permissionLauncher,
                intentLauncher,
                disAgreeAction = {
                    lockMode()
                },
                agreeAction = {
                    fileMode()
                })
        }
    }

    private fun fileMode() {
        binding.clLock.visibility = View.GONE
        binding.rv.visibility = View.VISIBLE
        binding.ivAll.visibility = View.VISIBLE
        binding.tvAll.visibility = View.VISIBLE
        binding.tvDelete.visibility = View.VISIBLE

        dialog = showLoadingDialog()
        loadData()
    }

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

    private fun loadData() {
        dialog.show()
        lifecycleScope.launch(Dispatchers.IO) {
            val list = dupImageStore()
            val dupDataList = arrayListOf<DupImageData>()
            val dupList = getDupImageList(list)
            dupList.forEach {
                dupDataList.add(DupImageData(dupList = it))
            }
            lifecycleScope.launch(Dispatchers.Main) {
                dialog.dismiss()
                adapter.setData(dupDataList)
                isEmptyUi()
            }
        }
    }

    private fun isEmptyUi() {

        val count = adapter.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
        }

    }
}