package com.base.filerecoveryrecyclebin.fragment

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.usage.StorageStatsManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context.STORAGE_STATS_SERVICE
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.filerecoveryrecyclebin.activity.MainActivity
import com.base.filerecoveryrecyclebin.activity.SettingActivity
import com.base.filerecoveryrecyclebin.activity.appmanager.AppManagerAnimationActivity
import com.base.filerecoveryrecyclebin.activity.appprocess.AppProcessAnimationActivity
import com.base.filerecoveryrecyclebin.activity.battery.BatteryInfoAnimationActivity
import com.base.filerecoveryrecyclebin.activity.junkclean.ScanJunk2Activity
import com.base.filerecoveryrecyclebin.activity.junkclean.ScanJunkActivity
import com.base.filerecoveryrecyclebin.activity.largefile.LargeFileAnimationActivity
import com.base.filerecoveryrecyclebin.activity.repeat.RepeatAnimationActivity
import com.base.filerecoveryrecyclebin.activity.screenshot.ScreenShotAnimationActivity
import com.base.filerecoveryrecyclebin.activity.whatsapp.WhatsAppCleanerAnimationActivity
import com.base.filerecoveryrecyclebin.databinding.FragmentHome3Binding
import com.base.filerecoveryrecyclebin.help.BaseFragment
import com.base.filerecoveryrecyclebin.help.KotlinExt.toFormatSize
import com.base.filerecoveryrecyclebin.help.PermissionHelp.checkStorePermission
import com.base.filerecoveryrecyclebin.utils.AppPreferences
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.io.File

class HomeFragment : BaseFragment<FragmentHome3Binding>() {
    private val TAG = "HomeFragment"

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


    @SuppressLint("SetTextI18n")
    override fun setView() {
        binding.tvTitle.text = "Dumpster"
        binding.lottie.repeatCount = ValueAnimator.INFINITE
        lifecycleScope.launch {
            (requireActivity() as MainActivity).photoSizeFlow.collectLatest { pair ->
                if (pair.first != 0L) {
                    binding.tvScreenshotSize.visibility = View.VISIBLE
                    binding.tvScreenshotSize.text = pair.first.toFormatSize()
                } else {
                    binding.tvScreenshotSize.visibility = View.GONE
                }

                if (pair.second != 0L) {
                    binding.tvDuplicateSize.visibility = View.VISIBLE
                    binding.tvDuplicateSize.text = pair.second.toFormatSize()
                } else {
                    binding.tvDuplicateSize.visibility = View.VISIBLE
                }
            }
        }
        showStorage()
    }

    var i = 0
    override fun setListener() {
        binding.flScan.setOnClickListener {
            val jumpJunkFirstAd = AppPreferences.getInstance().getString("isjunkPlayAd", "0").toInt()
            if (jumpJunkFirstAd == 1) {
                startActivity(Intent(requireContext(), ScanJunk2Activity::class.java))
            } else {
                startActivity(Intent(requireContext(), ScanJunkActivity::class.java))
            }

//            sendNotification(requireContext(), ConstObject.ID_JUNK_CLEAN_PUSH)
//            AppLovinSdk.getInstance( requireContext() ).showMediationDebugger()
        }
        binding.cardJunkClean.setOnClickListener {
            startActivity(Intent(requireContext(), ScanJunkActivity::class.java))
        }
        binding.cardWhatsapp.setOnClickListener {
            startActivity(Intent(requireContext(), WhatsAppCleanerAnimationActivity::class.java))
        }
        binding.cardAppManager.setOnClickListener {
            startActivity(Intent(requireContext(), AppManagerAnimationActivity::class.java))
        }
        binding.cardAppProcess.setOnClickListener {
            startActivity(Intent(requireContext(), AppProcessAnimationActivity::class.java))
        }
        binding.cardLargeFile.setOnClickListener {
            startActivity(Intent(requireContext(), LargeFileAnimationActivity::class.java))
        }
        binding.cardScreenshot.setOnClickListener {
            startActivity(Intent(requireContext(), ScreenShotAnimationActivity::class.java))
        }
        binding.cardDuplicate.setOnClickListener {
            startActivity(Intent(requireContext(), RepeatAnimationActivity::class.java))
        }
        binding.cardBattery.setOnClickListener {
            startActivity(Intent(requireContext(), BatteryInfoAnimationActivity::class.java))
        }

        binding.flSetting.setOnClickListener {
            startActivity(Intent(requireContext(), SettingActivity::class.java))
        }

        binding.ivArrowUp.setOnClickListener {
            val scrollDistance: Int = binding.nestedScrollView.getChildAt(0).height
            binding.nestedScrollView.smoothScrollTo(0, scrollDistance)
        }
        binding.tvTitle.setOnClickListener {
            i++
            if (i == 20) {
                copyUuidGid()
                i = 0
            }
        }

    }

    private fun copyUuidGid() {
        val uuid = AppPreferences.getInstance().getString("uuid", "")
        val gid = AppPreferences.getInstance().getString("gid", "")
        // 获取系统服务ClipboardManager
        val clipboard: ClipboardManager =
            requireContext().getSystemService(AppCompatActivity.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个ClipData对象，其中包含要复制的文本
        val clip = ClipData.newPlainText("uuid", "uuid=$uuid gid=$gid")
        // 将ClipData对象设置到剪贴板中
        clipboard.setPrimaryClip(clip)
        Toast.makeText(requireContext(), "copy", Toast.LENGTH_SHORT).show()
    }


    override fun onPause() {
        super.onPause()
        binding.lottie.pauseAnimation()

    }

    @SuppressLint("SetTextI18n")
    override fun onResume() {
        super.onResume()
        binding.lottie.resumeAnimation()
        if (requireContext().checkStorePermission()) {

        }
    }

    @SuppressLint("SetTextI18n")
    fun showStorage() {
        binding.llStorage.visibility = View.VISIBLE

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val storageStatsManager = requireContext().getSystemService(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.tvStorage.text = "${usedBytes.toFormatSize()} / ${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.tvStorage.text = "$usedSize / $totalSize"
        }
    }

}