package com.base.pdfviewerscannerwhite.ui.main

import android.annotation.SuppressLint
import android.app.usage.StorageStatsManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.os.storage.StorageManager
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.base.pdfviewerscannerwhite.bean.ConstObject.DO_LOCK_PDF
import com.base.pdfviewerscannerwhite.bean.ConstObject.DO_MERGE_PDF
import com.base.pdfviewerscannerwhite.bean.ConstObject.DO_SPLIT_PDF
import com.base.pdfviewerscannerwhite.bean.ConstObject.DO_UNLOCK_PDF
import com.base.pdfviewerscannerwhite.databinding.FragmentToolBinding
import com.base.pdfviewerscannerwhite.helper.BaseFragment
import com.base.pdfviewerscannerwhite.helper.WeatherUtils
import com.base.pdfviewerscannerwhite.ui.appprocess.AppProcessActivity
import com.base.pdfviewerscannerwhite.ui.appprocess.AppProcessLoadingActivity
import com.base.pdfviewerscannerwhite.ui.cleanjunk.ScanJunkActivity
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfActivity
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfBoxUtils
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfSelectActivity
import com.base.pdfviewerscannerwhite.ui.set.SetActivity
import com.base.pdfviewerscannerwhite.ui.view.PdfDialog.showPdfPwdDialog
import com.base.pdfviewerscannerwhite.ui.view.ProgressBean
import com.base.pdfviewerscannerwhite.ui.weather.WeatherInterface
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatSize
import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.utils.PermissionUtils.checkStorePermission
import com.base.pdfviewerscannerwhite.utils.getMediaAudioCountSize
import com.base.pdfviewerscannerwhite.utils.getMediaPhotoCountSize
import com.base.pdfviewerscannerwhite.utils.getMediaVideoCountSize
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File


class ToolFragment : BaseFragment<FragmentToolBinding>() {

    private val TAG = "ToolFragment"

    override val binding: FragmentToolBinding by lazy {
        FragmentToolBinding.inflate(layoutInflater)
    }


    @SuppressLint("SetTextI18n")
    override fun setView() {
        val bean = WeatherUtils.getWeatherEntity()?.list?.get(0)
        bean?.let {
            binding.tvWendu.text = (it.tempMax.toInt() + it.tempMin.toInt() / 2).toString()
        }
    }

    override fun setListener() {
        super.setListener()
        binding.llManager.setOnClickListener {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.setType("application/pdf")
            intent.flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION


            (requireActivity() as MainActivity).launcher.launch(intent) {
                val uri = it.data?.data ?: Uri.EMPTY

                lifecycleScope.launch(Dispatchers.IO) {
                    val state = PdfBoxUtils.checkPdfEncryption(uri.toString())
                    if (state == 0) {
                        launch(Dispatchers.Main) {
                            startActivity(Intent(requireContext(), PdfActivity::class.java).apply {
                                putExtra("uri", uri.toString())
                            })
                        }
                    } else {
                        launch(Dispatchers.Main) {
                            requireContext().showPdfPwdDialog(
                                state = state,
                                uri = uri.toString(),
                                isCheckPwd = true,
                                verificationAction = { pwd ->
                                    startActivity(Intent(requireContext(), PdfActivity::class.java).apply {
                                        putExtra("uri", uri.toString())
                                        putExtra("pwd", pwd)
                                    })
                                })
                        }
                    }
                }


            }
        }
        binding.llMerge.setOnClickListener {
            startActivity(Intent(requireContext(), PdfSelectActivity::class.java).apply {
                putExtra("doWhat", DO_MERGE_PDF)
            })
        }
        binding.llSplit.setOnClickListener {
            startActivity(Intent(requireContext(), PdfSelectActivity::class.java).apply {
                putExtra("doWhat", DO_SPLIT_PDF)
            })
        }
        binding.llLock.setOnClickListener {
            startActivity(Intent(requireContext(), PdfSelectActivity::class.java).apply {
                putExtra("doWhat", DO_LOCK_PDF)
            })
        }
        binding.llUnlock.setOnClickListener {
            startActivity(Intent(requireContext(), PdfSelectActivity::class.java).apply {
                putExtra("doWhat", DO_UNLOCK_PDF)
            })
        }
        binding.llSet.setOnClickListener {
            startActivity(Intent(requireContext(), SetActivity::class.java))
        }
        binding.llImagePdf.setOnClickListener {
            val mainActivity = (requireActivity() as MainActivity?)
            mainActivity ?: return@setOnClickListener
            mainActivity.useGmsScanFunction()
        }
        binding.llScan.setOnClickListener {
            val mainActivity = (requireActivity() as MainActivity?)
            mainActivity ?: return@setOnClickListener
            mainActivity.useGmsScanFunction()
        }
        binding.llProcess.setOnClickListener {
            startActivity(Intent(requireContext(), AppProcessLoadingActivity::class.java))
        }
        binding.tvClean.setOnClickListener {
            startActivity(Intent(requireContext(), ScanJunkActivity::class.java))
        }
        binding.llWeather.setOnClickListener {
            startActivity(Intent(requireContext(), WeatherInterface::class.java))
        }
    }

    override fun onResume() {
        super.onResume()
        if (requireContext().checkStorePermission()) {
            refreshData()
        }
    }


    @SuppressLint("SetTextI18n")
    fun refreshData() {

        if (preProgressList.isNullOrEmpty()) {
            lifecycleScope.launch(Dispatchers.IO) {
                LogEx.logDebug(TAG, "now load data")
                initAppVidePhotoMusicData(requireContext(),
                    {
                        lifecycleScope.launch(Dispatchers.Main) {
                            binding.tvUsedStorage.text = usedBytes.toFormatSize()
                            binding.tvTotalStorage.text = " / ${totalBytes.toFormatSize()}"
                            binding.tvPercent.text = "${usedBytes * 100 / totalBytes}"
                        }
                    },
                    {
                        launch(Dispatchers.Main) {
                            binding.colorProgress.animateProgress(progressList)
                        }
                    })
            }
        } else {
            lifecycleScope.launch(Dispatchers.Main) {
                LogEx.logDebug(TAG, "preload data")
                binding.tvUsedStorage.text = usedBytes.toFormatSize()
                binding.tvTotalStorage.text = " / ${totalBytes.toFormatSize()}"
                binding.tvPercent.text = "${usedBytes * 100 / totalBytes}"
                binding.colorProgress.animateProgress(preProgressList ?: arrayListOf())
                preProgressList = null
            }

        }


    }

    companion object {
        private var preProgressList: ArrayList<ProgressBean>? = arrayListOf()
        private val progressList = arrayListOf<ProgressBean>()
        private var usedBytes: Long = 0
        private var totalBytes: Long = 0

        fun initAppVidePhotoMusicData(context: Context, vararg uiAction: () -> Unit) {
            progressList.clear()

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                val storageStatsManager =
                    context.getSystemService(AppCompatActivity.STORAGE_STATS_SERVICE) as StorageStatsManager
                totalBytes = storageStatsManager.getTotalBytes(StorageManager.UUID_DEFAULT)
                usedBytes = totalBytes - storageStatsManager.getFreeBytes(StorageManager.UUID_DEFAULT)
            } else {
                val path1: File = Environment.getDataDirectory()
                val stat1 = StatFs(path1.path)
                val path2: File = Environment.getExternalStorageDirectory()
                val stat2 = StatFs(path2.path)
                totalBytes = (stat1.totalBytes + stat2.totalBytes)
                usedBytes = ((stat1.totalBytes + stat2.totalBytes) - (stat1.availableBytes + stat2.availableBytes))
            }

            runCatching { uiAction[0].invoke() }

            val videoPair = context.getMediaVideoCountSize()
            val picturePair = context.getMediaPhotoCountSize()
            val audioPair = context.getMediaAudioCountSize()

            val totalAngle = (usedBytes.toFloat() / totalBytes.toFloat()) * 360f
            val appSize = usedBytes - videoPair.second - picturePair.second - audioPair.second

            progressList.clear()
            val appAngle = (appSize * totalAngle / usedBytes).toFloat()
            val appBean = ProgressBean(0f, appAngle, "#FD412F")
            progressList.add(appBean)

            val videoAngle = (usedBytes * 0.01 * totalAngle / usedBytes)
            val videoBean = ProgressBean(appBean.sweepAngle, (appBean.sweepAngle + videoAngle).toFloat(), "#FDC734")
            progressList.add(videoBean)

            val photoAngle = (usedBytes * 0.01 * totalAngle / usedBytes)
            val photoBean = ProgressBean(videoBean.sweepAngle, (videoBean.sweepAngle + photoAngle).toFloat(), "#00BE78")
            progressList.add(photoBean)

            val audioAngle = (usedBytes * 0.01 * totalAngle / usedBytes)
            val audioBean = ProgressBean(photoBean.sweepAngle, (photoBean.sweepAngle + audioAngle).toFloat(), "#8238FD")
            progressList.add(audioBean)
            progressList.reverse()

            if (preProgressList != null) {
                preProgressList?.addAll(progressList)
            }
            runCatching { uiAction[1].invoke() }
        }
    }

}