package com.base.browserwhite.ui.fragment

import android.annotation.SuppressLint
import android.app.usage.StorageStatsManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.os.storage.StorageManager
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
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.mediabrowser.MediaBrowserActivity
import com.base.browserwhite.ui.adapter.MediaAdapter
import com.base.browserwhite.ui.views.DialogViews.showDeleteTipDialog
import com.base.browserwhite.ui.views.DialogViews.showMediaMoreDialog
import com.base.browserwhite.utils.IntentEx.shareAction
import com.base.browserwhite.utils.KotlinExt.toFormatSize
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.utils.MediaStoreUtils.getMediaApkSize
import com.base.browserwhite.utils.MediaStoreUtils.getMediaAudioSize
import com.base.browserwhite.utils.MediaStoreUtils.getMediaDocumentSize
import com.base.browserwhite.utils.MediaStoreUtils.getMediaPhotoSize
import com.base.browserwhite.utils.MediaStoreUtils.getMediaVideoSize
import com.base.browserwhite.utils.MediaStoreUtils.getMediaZipSize
import com.base.browserwhite.utils.MediaStoreUtils.getMediaFile
import com.base.browserwhite.utils.PermissionHelp.checkStorePermission
import com.base.browserwhite.utils.PermissionHelp.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

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

    @SuppressLint("QueryPermissionsNeeded")
    override fun setView() {
        showStorage()

        adapter = MediaAdapter(0,
            clickAction = {

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

        if (requireContext().checkStorePermission()) {
            initData()
        }
    }

    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 {
            val launcher = (requireActivity() as MainActivity).launcher
            requireContext().requestStorePermission(launcher) {
                if (it) {
                    initData()
                }
            }
        }
        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")
            })
        }


    }

    @SuppressLint("SetTextI18n")
    private fun showStorage() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val storageStatsManager = requireContext().getSystemService(AppCompatActivity.STORAGE_STATS_SERVICE) as StorageStatsManager

            Thread {
                val totalBytes = storageStatsManager.getTotalBytes(StorageManager.UUID_DEFAULT)
                val usedBytes = totalBytes - storageStatsManager.getFreeBytes(StorageManager.UUID_DEFAULT)
                binding.root.post {
                    binding.tvUsedStorage.text = usedBytes.toFormatSize()
                    binding.tvTotalStorage.text = " / " + totalBytes.toFormatSize()
                }
            }.start()

        } else {
            val path1: File = Environment.getDataDirectory()
            val stat1 = StatFs(path1.path)
            val path2: File = Environment.getExternalStorageDirectory()
            val stat2 = StatFs(path2.path)
            val totalSize = (stat1.totalBytes + stat2.totalBytes).toFormatSize()
            val usedSize = ((stat1.totalBytes + stat2.totalBytes) - (stat1.availableBytes + stat2.availableBytes)).toFormatSize()
            binding.tvUsedStorage.text = usedSize
            binding.tvTotalStorage.text = " / $totalSize"
        }
    }

    override fun onResume() {
        super.onResume()

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

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

        val pictureSize = requireContext().getMediaPhotoSize()
        val videoSize = requireContext().getMediaVideoSize()
        val documentSize = requireContext().getMediaDocumentSize()
        val apkSize = requireContext().getMediaApkSize()
        val audioSize = requireContext().getMediaAudioSize()
        val zipSize = requireContext().getMediaZipSize()

        launch(Dispatchers.Main) {
            binding.tvPhotoSize.text = pictureSize.toString()
            binding.tvVideoSize.text = videoSize.toString()
            binding.tvDocument.text = documentSize.toString()
            binding.tvApkSize.text = apkSize.toString()
            binding.tvAudioSize.text = audioSize.toString()
            binding.tvZipSize.text = zipSize.toString()
        }


        val mediaList = requireContext().getMediaFile().filter {
            val file = File(it.path)
            System.currentTimeMillis() - file.lastModified() <= 15L * 24 * 60 * 60 * 1000
        }
        LogEx.logDebug(TAG, "size=${mediaList.size}")
        launch(Dispatchers.Main) {
            adapter.setData(mediaList)
        }
    }


}