package com.base.browserwhite.ui.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.base.browserwhite.BuildConfig
import com.base.browserwhite.bean.MediaBean
import com.base.browserwhite.databinding.FragmentFileBinding
import com.base.browserwhite.ui.activity.MainActivity
import com.base.browserwhite.ui.activity.cleanjunk.ScanJunkActivity
import com.base.browserwhite.ui.activity.download.WebDownloadManagerActivity
import com.base.browserwhite.ui.activity.mediabrowser.MediaBrowserActivity
import com.base.browserwhite.ui.adapter.MediaAdapter
import com.base.browserwhite.ui.views.DialogViews.showDeleteTipDialog
import com.base.browserwhite.ui.views.DialogViews.showGerPermission
import com.base.browserwhite.ui.views.DialogViews.showMediaMoreDialog
import com.base.browserwhite.ui.views.ProgressBean
import com.base.browserwhite.utils.IntentEx.shareAction
import com.base.browserwhite.utils.KotlinExt.toFormatSize
import com.base.browserwhite.utils.MediaStoreUtils.getMediaApkCountSize
import com.base.browserwhite.utils.MediaStoreUtils.getMediaAudioCountSize
import com.base.browserwhite.utils.MediaStoreUtils.getMediaDocumentCountSize
import com.base.browserwhite.utils.MediaStoreUtils.getMediaFile
import com.base.browserwhite.utils.MediaStoreUtils.getMediaPhotoCountSize
import com.base.browserwhite.utils.MediaStoreUtils.getMediaVideoCountSize
import com.base.browserwhite.utils.MediaStoreUtils.getMediaZipCountSize
import com.base.browserwhite.utils.PermissionUtils.checkStorePermission
import com.base.browserwhite.utils.PermissionUtils.requestStorePermission
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File


class FileFragment : BaseFragment<FragmentFileBinding>() {

    private val TAG = "FileFragment"

    private lateinit var adapter: MediaAdapter
    private val progressList = arrayListOf<ProgressBean>()

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

    @SuppressLint("QueryPermissionsNeeded", "SetTextI18n")
    override fun setView() {
        val mainActivity = (requireActivity() as MainActivity)
        binding.tvUsedStorage.text = mainActivity.usedBytes.toFormatSize()
        binding.tvTotalStorage.text = " / ${mainActivity.totalBytes.toFormatSize()}"
        binding.tvPercent.text = "${(mainActivity.usedBytes * 100f / mainActivity.totalBytes).toInt()}"

        adapter = MediaAdapter(0,
            clickAction = {

            },
            moreAction = { view, bean ->
                moreAction(requireContext(), view, bean, adapter)
            })
        binding.rvRecent.adapter = adapter
    }

    companion object {
        @SuppressLint("QueryPermissionsNeeded")
        fun moreAction(context: Context, archView: View, bean: MediaBean, adapter: MediaAdapter) {
            context.showMediaMoreDialog(archView,
                deleteAction = {
                    context.showDeleteTipDialog {
                        runCatching { File(bean.path).delete() }
                        adapter.removeData(bean)
                    }
                },
                shareAction = {
                    context.shareAction(bean.uri, bean.mimeType)
                })
        }
    }

    override fun setListener() {
        super.setListener()

        binding.llPermission.setOnClickListener {
            requireContext().showGerPermission(
                desc = "This feature requires access to your storage to scan your files and summarize your file types. We will not transfer your data to any third-party services. Please grant permission so that we can provide you with better services.",
                deny = {}, allow = {
                    val launcher = (requireActivity() as MainActivity).launcher
                    requireContext().requestStorePermission(launcher) {

                    }
                })

        }
        binding.tvClean.setOnClickListener {
            startActivity(Intent(requireContext(), ScanJunkActivity::class.java))
        }
        binding.llPicture.setOnClickListener {
            requireActivity().startActivity(Intent(requireContext(), MediaBrowserActivity::class.java).apply {
                putExtra("tittle", "Picture")
            })
        }
        binding.llVideo.setOnClickListener {
            requireActivity().startActivity(Intent(requireContext(), MediaBrowserActivity::class.java).apply {
                putExtra("tittle", "Video")
            })
        }
        binding.llDocument.setOnClickListener {
            requireActivity().startActivity(Intent(requireContext(), MediaBrowserActivity::class.java).apply {
                putExtra("tittle", "Document")
            })
        }
        binding.llApk.setOnClickListener {
            requireActivity().startActivity(Intent(requireContext(), MediaBrowserActivity::class.java).apply {
                putExtra("tittle", "APK")
            })
        }
        binding.llMusic.setOnClickListener {
            requireActivity().startActivity(Intent(requireContext(), MediaBrowserActivity::class.java).apply {
                putExtra("tittle", "Music")
            })
        }
        binding.llZip.setOnClickListener {
            requireActivity().startActivity(Intent(requireContext(), MediaBrowserActivity::class.java).apply {
                putExtra("tittle", "Zip")
            })
        }
        binding.llDownload.setOnClickListener {
            startActivity(Intent(requireContext(), WebDownloadManagerActivity::class.java))
//            startActivity(Intent(requireContext(), WebBrowserActivity::class.java).apply {
//                putExtra("url", "https://mixkit.co/free-stock-video/girl-dancing-happily-in-a-field-of-flowers-4702/")
//            })
        }


    }


    override fun onResume() {
        super.onResume()

        if (requireContext().checkStorePermission()) {
            binding.llPermission.visibility = View.GONE
            initData()
        } else {
            simulateProgress()
            binding.llPermission.visibility = View.VISIBLE
        }
    }

    private fun simulateProgress() {
        val mainActivity = (requireActivity() as MainActivity)
        val totalAngle = (mainActivity.usedBytes.toFloat() / mainActivity.totalBytes.toFloat()) * 360f
        val appSize = mainActivity.usedBytes - mainActivity.usedBytes * 0.01 * 3

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

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

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

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

        binding.colorProgress.animateProgress(
//                listOf(
//                    ProgressBean(155f, 180f, "#8238FD"),//music
//                    ProgressBean(108f, 155f, "#00BE78"),//photo
//                    ProgressBean(65f, 108f, "#FDC734"),//vide
//                    ProgressBean(0f, 65f, "#FD412F"),//app
//                )
            progressList
        )
    }

    private fun initData() = lifecycleScope.launch(Dispatchers.IO) {

        val picturePair = requireContext().getMediaPhotoCountSize()
        val videoPair = requireContext().getMediaVideoCountSize()
        val documentSize = requireContext().getMediaDocumentCountSize()
        val apkSize = requireContext().getMediaApkCountSize()
        val audioPair = requireContext().getMediaAudioCountSize()
        val zipSize = requireContext().getMediaZipCountSize()

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

        progressList.clear()
        var appAngle = (appSize * totalAngle / mainActivity.usedBytes)
        val random = (appAngle / 5).toInt()
        appAngle -= random
        val appBean = ProgressBean(0f, appAngle, "#FD412F")
        progressList.add(appBean)

        val videoAngle = (videoPair.second * totalAngle / mainActivity.usedBytes) + random / 3
        val videoBean = ProgressBean(appBean.sweepAngle, appBean.sweepAngle + videoAngle, "#FDC734")
        progressList.add(videoBean)

        val photoAngle = (picturePair.second * totalAngle / mainActivity.usedBytes) + random / 3
        val photoBean = ProgressBean(videoBean.sweepAngle, videoBean.sweepAngle + photoAngle, "#00BE78")
        progressList.add(photoBean)

        val audioAngle = (audioPair.second * totalAngle / mainActivity.usedBytes) + random / 3
        val audioBean = ProgressBean(photoBean.sweepAngle, photoBean.sweepAngle + audioAngle, "#8238FD")
        progressList.add(audioBean)
        progressList.reverse()

        launch(Dispatchers.Main) {
            binding.colorProgress.animateProgress(
//                listOf(
//                    ProgressBean(155f, 180f, "#8238FD"),//music
//                    ProgressBean(108f, 155f, "#00BE78"),//photo
//                    ProgressBean(65f, 108f, "#FDC734"),//vide
//                    ProgressBean(0f, 65f, "#FD412F"),//app
//                )
                progressList
            )
            binding.tvPhotoSize.text = picturePair.first.toString()
            binding.tvVideoSize.text = videoPair.first.toString()
            binding.tvAudioSize.text = audioPair.first.toString()
            binding.tvDocument.text = documentSize.toString()
            binding.tvApkSize.text = apkSize.toString()
            binding.tvZipSize.text = zipSize.toString()
        }

        binding.colorProgress.finishAnimation = {
            initMediaData()
        }

    }

    private fun initMediaData() = Thread {
        val list = requireContext().getMediaFile().filter {
            val file = File(it.path)
            if (BuildConfig.DEBUG) {
                true
            } else {
                System.currentTimeMillis() - file.lastModified() <= 15L * 24 * 60 * 60 * 1000
            }
        }
        binding.root.post {
            if (list.isEmpty()) {
                binding.tvTitleRecent.visibility = View.GONE
            }
            adapter.setData(list)
        }
    }.start()


}