package com.ux.video.file.filerecovery.main

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.LinearGradient
import android.graphics.Shader
import android.os.Build
import android.os.Environment
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.core.view.isVisible
import com.ux.video.file.filerecovery.R
import com.ux.video.file.filerecovery.base.BaseActivity
import com.ux.video.file.filerecovery.databinding.ActivityMainBinding
import com.ux.video.file.filerecovery.main.ScanSelectTypeActivity
import com.ux.video.file.filerecovery.photo.DateFilterPopupWindows
import com.ux.video.file.filerecovery.photo.DatePickerDialogFragment
import com.ux.video.file.filerecovery.utils.ScanManager

class MainActivity : BaseActivity<ActivityMainBinding>() {
    private var dialogCustomerDateStart:DatePickerDialogFragment? = null
     private   var dialogPermission: PermissionDialogFragment? = null
    //是否正确引导用户打开所有文件管理权限
    private var isRequestPermission = false
    private var currentGoType = ScanSelectTypeActivity.Companion.VALUE_PHOTO
    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            var isAllOK = true
            permissions.entries.forEach { entry ->
                val permission = entry.key
                val granted = entry.value
                if (granted) {

                } else {
                    isAllOK = false
                }
            }
            ScanManager.showLog("权限", "====isAllOK=${isAllOK}")
            if (isAllOK) {
                startScan()
            }


        }

    override fun inflateBinding(inflater: LayoutInflater) = ActivityMainBinding.inflate(inflater)


    override fun initView() {
        super.initView()
        onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    ScanManager.showLog("权限", "====0000000")
                    if (binding.layoutPermission.isVisible) {
                        ScanManager.showLog("权限", "====111111")
                        binding.layoutPermission.visibility = View.GONE
                    } else {
                        ScanManager.showLog("权限", "====222222222222")
                        finish()
                    }
                }
            })
    }

    override fun initData() {
        super.initData()
        initTitleColor()
        binding.run {
            allow.setOnClickListener {

            }
            layoutPhoto.setOnClickListener {
                currentGoType = ScanSelectTypeActivity.Companion.VALUE_PHOTO
                intentCheck()
            }
            layoutVideo.setOnClickListener {
                currentGoType = ScanSelectTypeActivity.Companion.VALUE_VIDEO
                intentCheck()
            }
            layoutAudio.setOnClickListener {
                currentGoType = ScanSelectTypeActivity.Companion.VALUE_AUDIO
                intentCheck()
            }
            layoutDocument.setOnClickListener {
                currentGoType = ScanSelectTypeActivity.Companion.VALUE_DOCUMENT
                intentCheck()
            }
        }
        binding.tvTitle.setOnClickListener {

            showDatePicker()

        }
        binding.btnScanAllPhoto.setOnClickListener {

            startActivity(Intent(this@MainActivity, ScanSelectTypeActivity::class.java).apply {
                putExtra(
                    ScanSelectTypeActivity.Companion.KEY_FILE_TYPE,
                    ScanSelectTypeActivity.Companion.VALUE_PHOTO
                )
            })
        }
        binding.btnScanAllVideo.setOnClickListener {

            startActivity(Intent(this@MainActivity, ScanSelectTypeActivity::class.java).apply {
                putExtra(
                    ScanSelectTypeActivity.Companion.KEY_FILE_TYPE,
                    ScanSelectTypeActivity.Companion.VALUE_VIDEO
                )
            })
        }
        binding.btnScanAllAudio.setOnClickListener {

            startActivity(Intent(this@MainActivity, ScanSelectTypeActivity::class.java).apply {
                putExtra(
                    ScanSelectTypeActivity.Companion.KEY_FILE_TYPE,
                    ScanSelectTypeActivity.Companion.VALUE_AUDIO
                )
            })
        }

        binding.btnScanAllFile.setOnClickListener {
//            val results = mutableListOf<ResultPhotos>()
            val root = Environment.getExternalStorageDirectory()

//            ScanManager.scanAllDocuments(root, results)
//            ScanRepository.instance.setResults(results)




//            startActivity(Intent(this@MainActivity,DocumentsScanResultActivity::class.java))
//
//            results.forEach { doc ->
//                ScanManager.showLog("FileScan", "目录: ${doc.dirName}, 文件数: ${doc.allFiles.size}")
//                doc.allFiles.forEach { file ->
//                    ScanManager.showLog("FileScan", " -> 文件: ${file.targetFile.isHidden} ")
//                }
//            }
        }
    }

    private fun initTitleColor() {

        binding.tvTitle.apply {
            // 渐变色
            val width = paint.measureText(text.toString())
            val shader = LinearGradient(
                0f, 0f, width, textSize,
                intArrayOf(getColor(R.color.color_title_start_color),getColor(R.color.color_title_end_color)),
                null,
                Shader.TileMode.CLAMP
            )
            paint.shader = shader

            setShadowLayer(2f, 2f, 2f, getColor(R.color.color_title_start_color))

        }


    }

    override fun onResume() {
        super.onResume()
        if (isRequestPermission && hasAllFilesAccess(this)) {
            isRequestPermission = false
            ScanManager.showLog("--", "-------onResume")
            startScan()
            binding.layoutPermission.visibility = View.GONE
        }
    }

    private fun intentCheck() {
        if (!hasAllFilesAccess(this)) {
            requestPermission()
        } else {
            ScanManager.showLog("--", "-------权限已经授予")
            startScan()
        }
    }

    /**
     * 判断文件管理权限
     */
    private fun hasAllFilesAccess(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            val read = ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
            val write = ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
            read && write
        }
    }

    private fun requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            dialogPermission = dialogPermission?: PermissionDialogFragment{
                try {
                    val intent =
                        Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply {
                            data = "package:${packageName}".toUri()
                        }
                    startActivity(intent)
                } catch (e: Exception) {
                    val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
                    startActivity(intent)
                }
                isRequestPermission = true
            }
            dialogPermission?.show(supportFragmentManager,"")
        } else {
            requestPermissionLauncher.launch(
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
            )
        }
    }

    private fun startScan() {
        startActivity(Intent(this@MainActivity, ScanSelectTypeActivity::class.java).apply {
            putExtra(ScanSelectTypeActivity.Companion.KEY_FILE_TYPE, currentGoType)
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.layoutPermission.isVisible = false
    }


    fun showDatePicker() {
//        dialogCustomerDateStart = dialogCustomerDateStart?: DateFilterPopupWindows(this){}
//        dialogCustomerDateStart?.show(supportFragmentManager,"")
    }
}