package com.zxhy.hfilemanagermaster.internalstorage

import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.KeyEvent
import android.view.KeyEvent.ACTION_UP
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.navigation.fragment.findNavController
import com.example.hfilemanagermaster.R
import com.example.hfilemanagermaster.databinding.ActivityInternalStorageBinding
import com.zxhy.hfilemanagermaster.OverviewActivity
import com.zxhy.hfilemanagermaster.knife.Saf
import com.zxhy.hfilemanagermaster.knife.file2MediaDataC
import com.zxhy.hfilemanagermaster.knife.getPublicMedia
import com.zxhy.hfilemanagermaster.permission.IntentLauncher
import com.zxhy.hfilemanagermaster.permission.PermissionLauncher
import com.zxhy.hfilemanagermaster.permission.requestStoreFollow
import com.zxhy.hfilemanagermaster.permission.settingManageExternalStorage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

// 额外储存管理权限，读几个图片和视频
class InternalStorageActivity : AppCompatActivity() {

    private lateinit var binding: ActivityInternalStorageBinding
    private lateinit var saf: Saf
    private lateinit var intentLauncher: IntentLauncher
    private lateinit var permissionLauncher: PermissionLauncher
    private lateinit var fileAdapter: FileAdapter
    private var currentMode = 0 //0非可选模式  1可选模式
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        saf = Saf(this)
        intentLauncher = IntentLauncher(this)
        binding = ActivityInternalStorageBinding.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.tvSet.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (!Environment.isExternalStorageManager()) {
                    val uri = Uri.parse("package:$packageName")
                    val intent = settingManageExternalStorage(uri)
                    intentLauncher.launch(intent) {
                        val flag = Environment.isExternalStorageManager()
                        if (flag) {
                            fileMode()
//                            toast("已设置额外储存管理")
                        } else {
//                            toast("未设置额外储存管理")
                            lockMode()
                        }
                    }
                } else {
//                    toast("已设置额外储存管理")
                    fileMode()
                }
            } else {
                requestStoreFollow(permissionLauncher, intentLauncher) { fileMode() }
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                fileMode()
            } else {
                lockMode()
            }
        } else {
            fileMode()
        }
    }

    private fun fileMode() {
        binding.clLock.visibility = View.GONE
        binding.clShow.visibility = View.VISIBLE
        fileAdapter = FileAdapter {
            binding.ivAll.isSelected = it
        }
        binding.ivAll.setOnClickListener {
            it.isSelected = fileAdapter.setToggleSelect()
        }
        binding.rv.adapter = fileAdapter
        File("").renameTo(File(""))
        loadFile()

        noSelectMode()
    }

    private fun loadFile() {
        lifecycleScope.launch(Dispatchers.IO) {
            val rootList = Environment.getExternalStorageDirectory().listFiles()
            val list = rootList?.map {
                it.file2MediaDataC(this@InternalStorageActivity)
            } ?: listOf()

            lifecycleScope.launch(Dispatchers.Main) {
                fileAdapter.setData(list)
            }
        }
    }

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

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (currentMode == 1) {
            noSelectMode()
            fileAdapter.showNoSelect()
            return false
        }
        var flag = false
        if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == ACTION_UP) {
            flag = fileAdapter.beforePage(this)
        }
        return if (flag) {
            false
        } else {
            super.dispatchKeyEvent(event)
        }
    }


    private fun selectMode() {
        currentMode = 1
        binding.ivWrite.visibility = View.GONE
        binding.ivNewFolder.visibility = View.VISIBLE

        binding.ivAll.visibility = View.VISIBLE
        binding.tvAll.visibility = View.VISIBLE
    }

    private fun noSelectMode() {
        currentMode = 0
        binding.ivWrite.visibility = View.VISIBLE
        binding.ivNewFolder.visibility = View.VISIBLE

        binding.ivAll.visibility = View.GONE
        binding.tvAll.visibility = View.GONE

        binding.ivWrite.setOnClickListener {
            fileAdapter.showSelect()
            selectMode()
        }
    }
}