package com.base.superfilemanager.fragment

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Environment
import android.os.StatFs
import android.util.Log
import android.view.animation.LinearInterpolator
import android.widget.ScrollView
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.SPUtils
import com.base.superfilemanager.activity.AppManagerActivity
import com.base.superfilemanager.activity.BatteryInfoActivity
import com.base.superfilemanager.activity.LargeFileCleanActivity
import com.base.superfilemanager.activity.MainActivity
import com.base.superfilemanager.activity.NetWorkActivity
import com.base.superfilemanager.activity.RecentAppActivity
import com.base.superfilemanager.activity.RepeaterdPhotoActivity
import com.base.superfilemanager.activity.ScanJunkActivity
import com.base.superfilemanager.activity.SpeakerCleanerActivity
import com.base.superfilemanager.activity.photocompress.photo.StartCompressionPhotoActivity
import com.base.superfilemanager.databinding.FragmentLayoutHomeBinding
import com.base.superfilemanager.helps.BaseFragment
import com.base.superfilemanager.helps.KotlinExt.setOnClickListener
import com.base.superfilemanager.helps.KotlinExt.toFormatSize
import com.base.superfilemanager.helps.NetWorkSpeed
import com.base.superfilemanager.notificationclean.NotificationCleanActivity
import com.base.superfilemanager.notificationclean.NotificationGuestActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random

class HomeFragment : BaseFragment<FragmentLayoutHomeBinding>() {

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


    override fun setView() {
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        ValueAnimator.ofFloat(0f, 360f).run {
            duration = 1000
            repeatMode = ValueAnimator.RESTART
            repeatCount = ValueAnimator.INFINITE
            interpolator = LinearInterpolator()
            addUpdateListener {
                runCatching {
                    binding.idImgXuanzhuan.rotation = it.animatedValue as Float
                }
            }
            start()
        }
        initStorage()
    }

    @SuppressLint("SetTextI18n")
    override fun setListener() {
        binding.idImgSl.setOnClickListener {
            binding.idScrollView.fullScroll(ScrollView.FOCUS_DOWN)
        }
        listOf(binding.idCleanJunk, binding.idFlClean, binding.idCleanUp).setOnClickListener {
            startActivity(Intent(requireContext(), ScanJunkActivity::class.java))
        }
        binding.idLargeFile.setOnClickListener {
            startActivity(Intent(requireContext(), LargeFileCleanActivity::class.java))
        }
        binding.idImgCompress.setOnClickListener {
            startActivity(Intent(requireActivity(), StartCompressionPhotoActivity::class.java))
        }
        binding.idSimilarPhone.setOnClickListener {
            startActivity(Intent(requireContext(), RepeaterdPhotoActivity::class.java))
        }
        binding.idAppManager.setOnClickListener {
            startActivity(Intent(requireContext(), AppManagerActivity::class.java))
        }
        binding.idBatteryInfo.setOnClickListener {
            startActivity(Intent(requireContext(), BatteryInfoActivity::class.java))
        }
        binding.idSpeakCleaner.setOnClickListener {
            startActivity(Intent(requireContext(), SpeakerCleanerActivity::class.java))

        }
        binding.idNetworkTraffic.setOnClickListener {
            startActivity(Intent(requireContext(), NetWorkActivity::class.java))
        }
        binding.idRecentAppUse.setOnClickListener {
            startActivity(Intent(requireContext(), RecentAppActivity::class.java))
        }
        binding.idNotificationCleaner.setOnClickListener {
            if (SPUtils.getInstance().getBoolean("notification_guest", false)) {
                startActivity(Intent(requireActivity(), NotificationCleanActivity::class.java))
            } else {
                startActivity(Intent(requireActivity(), NotificationGuestActivity::class.java))
            }
        }

        MainScope().launch(Dispatchers.IO) {
            NetWorkSpeed.startMoritor()
        }
    }

    var totalsize = 0L

    @SuppressLint("SetTextI18n")
    private fun initStorage() {
        val stat = StatFs(Environment.getExternalStorageDirectory().path)
        val totalSize = f()
        val availableSize = b()
        val usedSize = totalSize - availableSize
        val usedPercentage = usedSize.toFloat() / totalSize * 100
        binding.idTvOccupied.text = "${usedSize.toFormatSize()}/ ${totalSize.toFormatSize()}"
    }

    fun f(): Long {
        return if (totalsize > 0) {
            totalsize
        } else try {
            val statFs = StatFs(Environment.getExternalStorageDirectory().path)
            val statFs2 = StatFs(Environment.getRootDirectory().path)
            Log.i(
                "storeByteDebug",
                "store1: " + statFs2.blockSizeLong * statFs2.blockCountLong + "====store2: " + statFs.blockSizeLong * statFs.blockCountLong
            )
            var blockSizeLong =
                statFs2.blockSizeLong * statFs2.blockCountLong + statFs.blockSizeLong * statFs.blockCountLong

            blockSizeLong = getClosestPowerOfTwo(blockSizeLong)
            totalsize = blockSizeLong
            blockSizeLong

        } catch (e10: java.lang.Exception) {
            0L
        }
    }

    fun a(j10: Long): Long {
        var j10 = j10
        var i7 = 0
        while (true) {
            val j11: Long = 1000
            if (j10 < j11) {
                break
            }
            j10 /= j11
            i7++
        }
        for (i10 in 0 until i7) {
            j10 *= 1024
        }
        return j10
    }

    fun b(): Long {
        try {
            val statFs = StatFs(Environment.getExternalStorageDirectory().path)
            val statFs2 = StatFs(Environment.getRootDirectory().path)
            val blackSize =
                statFs2.blockSizeLong * statFs2.availableBlocksLong + statFs.blockSizeLong * statFs.availableBlocksLong
            return a(blackSize)
        } catch (e10: Exception) {
            return 0L
        }
    }

    fun getClosestPowerOfTwo(size: Long): Long {
        var powerOfTwo: Long = 1
        while (powerOfTwo < size) {
            powerOfTwo *= 2
        }
        return powerOfTwo
    }
}