package com.zxhy.hfilemanagermaster.largefile

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 androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.hfilemanagermaster.R
import com.example.hfilemanagermaster.databinding.ActivityLargeFileBinding
import com.zxhy.hfilemanagermaster.data.MediaDataC
import com.zxhy.hfilemanagermaster.dialog.showLoadingDialog
import com.zxhy.hfilemanagermaster.dialog.showOperationDialog
import com.zxhy.hfilemanagermaster.emptyfile.EmptyFileAdapter
import com.zxhy.hfilemanagermaster.knife.deleteDirectory
import com.zxhy.hfilemanagermaster.knife.emptyFile
import com.zxhy.hfilemanagermaster.knife.largeFile
import com.zxhy.hfilemanagermaster.knife.largeImage
import com.zxhy.hfilemanagermaster.knife.largePhoto
import com.zxhy.hfilemanagermaster.knife.largeVideo
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 LargeFileActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLargeFileBinding
    private lateinit var mediaSelectAdapter: LagerFileSelectorAdapter
    private lateinit var imageSelectorAdapter: LargeImageSelectorAdapter
    private lateinit var videoSelectorAdapter: LargeVideoSelectorAdapter
    private lateinit var permissionLauncher: PermissionLauncher
    private lateinit var intentLauncher: IntentLauncher
    private var currentMode = 0//0 文件 1图片 2视频

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        intentLauncher = IntentLauncher(this)
        permissionLauncher = PermissionLauncher(this)
        binding = ActivityLargeFileBinding.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()
        }

        binding.tvDelete.setOnClickListener {
            val list = when (currentMode) {
                0 -> mediaSelectAdapter.getSelectData()
                1 -> imageSelectorAdapter.getSelectData()
                2 -> videoSelectorAdapter.getSelectData()
                else -> listOf()
            }
            val num = list.size
            if (num == 0) return@setOnClickListener
            this.alert("Currently selected $num items, are you sure to delete them") {
                positiveButton("confirm") { dialog ->
                    deleteFiles(list)
                    dialog.dismiss()
                }
                negativeButton("cancel") { dialog ->
                    dialog.dismiss()
                }
                //禁止取消
                isCancel(false)
            }


        }
        binding.ivAll.setOnClickListener { view ->
            when (currentMode) {
                0 -> view.isSelected = mediaSelectAdapter.setToggleSelect()
                1 -> view.isSelected = imageSelectorAdapter.setToggleSelect()
                2 -> view.isSelected = videoSelectorAdapter.setToggleSelect()
            }
        }

        binding.tvFile.setOnClickListener {
            if (currentMode != 0)
                fileMode()
        }
        binding.tvImage.setOnClickListener {
            if (currentMode != 1)
                imageMode()
        }
        binding.tvVideo.setOnClickListener {
            if (currentMode != 2)
                videoMode()
        }

        if (storePermissionCheck()) {
            imageMode()
        } 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

        currentMode = 0
        binding.tvFile.setTextColor(ContextCompat.getColor(this, R.color.color_333333))
        binding.tvImage.setTextColor(ContextCompat.getColor(this, R.color.color_999999))
        binding.tvVideo.setTextColor(ContextCompat.getColor(this, R.color.color_999999))

        mediaSelectAdapter = LagerFileSelectorAdapter {
            binding.ivAll.isSelected = it
        }
        binding.rv.layoutManager = LinearLayoutManager(this)
        binding.rv.adapter = mediaSelectAdapter

        loadLargeFileData()
    }

    private fun loadLargeFileData() {
        val loadDialog = showLoadingDialog()
        largeFile(this,
            onDoAction = { list ->
                runOnUiThread {
                    loadDialog.dismiss()
                    mediaSelectAdapter.addData(list)
                }
            }, finishAction = {
                loadDialog.dismiss()
                runOnUiThread { isEmptyUi() }
            })
    }

    private fun imageMode() {
        currentMode = 1
        binding.tvFile.setTextColor(ContextCompat.getColor(this, R.color.color_999999))
        binding.tvImage.setTextColor(ContextCompat.getColor(this, R.color.color_333333))
        binding.tvVideo.setTextColor(ContextCompat.getColor(this, R.color.color_999999))

        imageSelectorAdapter = LargeImageSelectorAdapter {
            binding.ivAll.isSelected = it
        }
        binding.rv.layoutManager = GridLayoutManager(this, 3)
        binding.rv.adapter = imageSelectorAdapter
        loadLargeImageData()
    }

    private fun loadLargeImageData() {
        val loadDialog = showLoadingDialog()
        largeImage(
            this,
            onDoAction = { list ->
                runOnUiThread {
                    loadDialog.dismiss()
                    imageSelectorAdapter.addData(list)
                }
            }, finishAction = {
                runOnUiThread {
                    loadDialog.dismiss()
                    isEmptyUi()
                }
            })
    }

    private fun videoMode() {
        currentMode = 2
        binding.tvFile.setTextColor(ContextCompat.getColor(this, R.color.color_999999))
        binding.tvImage.setTextColor(ContextCompat.getColor(this, R.color.color_999999))
        binding.tvVideo.setTextColor(ContextCompat.getColor(this, R.color.color_333333))


        videoSelectorAdapter = LargeVideoSelectorAdapter {
            binding.ivAll.isSelected = it
        }
        binding.rv.layoutManager = GridLayoutManager(this, 3)
        binding.rv.adapter = videoSelectorAdapter

        loadLargeVideoData()
    }

    private fun loadLargeVideoData() {
        val loadDialog = showLoadingDialog()

        largeVideo(
            this,
            onDoAction = { list ->
                runOnUiThread {
                    loadDialog.dismiss()
                    videoSelectorAdapter.addData(list)
                }
            }, finishAction = {
                runOnUiThread {
                    loadDialog.dismiss()
                    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)
                }
            }
            runOnUiThread {
                lifecycleScope.launch(Dispatchers.Main) {
                    val dialog = showOperationDialog(R.mipmap.dads_889562, "delete success!") {}
                    delay(200)
                    dialog.dismiss()

                    when (currentMode) {
                        0 -> mediaSelectAdapter.removeData(files)
                        1 -> imageSelectorAdapter.removeData(files)
                        2 -> videoSelectorAdapter.removeData(files)
                    }
                    isEmptyUi()
                }
            }

        } catch (e: Exception) {
            e.printStackTrace()
            runOnUiThread {
                toast("delete failed")
            }
        }
    }.start()

    private fun isEmptyUi() {
        val count = when (currentMode) {
            0 -> mediaSelectAdapter.itemCount
            1 -> imageSelectorAdapter.itemCount
            2 -> videoSelectorAdapter.itemCount
            else -> 0
        }

        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
        }

    }
}