package com.zxhyis.toolss.ui.home

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.os.StatFs
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.ScrollView
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.SPUtils
import com.zxhyis.toolss.ad.bean.PushCfg
import com.zxhyis.toolss.ad.queryDataStoreBlock
import com.zxhyis.toolss.ad.saveDataStore
import com.zxhyis.toolss.base.TopFragment
import com.zxhyis.toolss.common.notification.NotificationHelper.postActionNotification
import com.zxhyis.toolss.cx.FileHelps.toFormatSize
import com.zxhyis.toolss.databinding.FragmentHome2Binding
import com.zxhyis.toolss.logic.RamMemoryEx.getMemoryUsage
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.logic.toast
import com.zxhyis.toolss.ui.page.BatteryInfoActivity
import com.zxhyis.toolss.ui.page.NetWorkActivity
import com.zxhyis.toolss.ui.page.NetworkSpeed
import com.zxhyis.toolss.ui.page.PrepareScanActivity
import com.zxhyis.toolss.ui.page.RepeaterdPhotoActivity
import com.zxhyis.toolss.ui.page.SpeakerCleanerActivity
import com.zxhyis.toolss.ui.page.VirusActivity
import com.zxhyis.toolss.ui.page.applock.AppLockManagerActivity
import com.zxhyis.toolss.ui.page.appmanager.AppManager2Activity
import com.zxhyis.toolss.ui.page.bigfileclean.BigFileCleanActivity
import com.zxhyis.toolss.ui.page.notifaction.NotificationCleanActivity
import com.zxhyis.toolss.ui.page.notifaction.NotificationGuestActivity
import com.zxhyis.toolss.ui.page.photocompress.photo.StartCompressionPhotoActivity
import com.zxhyis.toolss.ui.page.recentusage.RecentAppActivity
import com.zxhyis.toolss.ui.receiver.BatteryReceiver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random


class NewHomeFragment : TopFragment<FragmentHome2Binding>() {
    override fun createBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentHome2Binding {
        return FragmentHome2Binding.inflate(inflater, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }

    @SuppressLint("SetTextI18n")
    private fun init() {
        mK.root.updatePadding(top = BarUtils.getStatusBarHeight())
        ValueAnimator.ofFloat(0f, 360f).run {
            duration = 1000
            repeatMode = ValueAnimator.RESTART
            repeatCount = ValueAnimator.INFINITE
            interpolator = LinearInterpolator()
            addUpdateListener {
                mK.idImgXuanzhuan.rotation = it.animatedValue as Float
            }
            start()
        }
//        mK.idTvOccupied.text = "13.58GB / 118GB"
        mK.idFlClean.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), PrepareScanActivity::class.java))
        }
        mK.idCleanUp.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), PrepareScanActivity::class.java))
        }
        mK.idCleanJunk.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), PrepareScanActivity::class.java))
            saveDian("dianJunk")
        }
        mK.idAntivirus.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), VirusActivity::class.java))
            saveDian("dianAntivirus")
        }
        mK.idNetworkTraffic.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), NetWorkActivity::class.java))
            saveDian("dianNetworkTraffic")
        }
        mK.idRecentApp.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), RecentAppActivity::class.java))
            saveDian("dianRecentApp")
        }
        mK.idAppManager.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), AppManager2Activity::class.java))
            saveDian("dianAppManager")
        }
        mK.idBatteryInfo.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), BatteryInfoActivity::class.java))
            saveDian("dianBatteryInfo")
        }
        mK.idNotificationCleaner.setOnClick(javaClass.simpleName) {
            if (SPUtils.getInstance().getBoolean("notification_guest", false)) {
                startActivity(Intent(requireActivity(), NotificationCleanActivity::class.java))
            } else {
                startActivity(Intent(requireActivity(), NotificationGuestActivity::class.java))
            }
        }
        mK.idSpeakCleaner.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), SpeakerCleanerActivity::class.java))
        }
        mK.idRecentAppUse.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), RecentAppActivity::class.java))
        }
        mK.idSmilarPhotos.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), RepeaterdPhotoActivity::class.java))
            // startActivity(Intent(requireActivity(), SimilarPhotosActivity::class.java))
        }
        mK.idPhotoCompress.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), StartCompressionPhotoActivity::class.java))
        }
        mK.idLargeFile.setOnClick(javaClass.simpleName) {
            startActivity(Intent(requireActivity(), BigFileCleanActivity::class.java))
        }
        mK.idAppLock.setOnClick(javaClass.simpleName){
            startActivity(Intent(requireActivity(), AppLockManagerActivity::class.java))
        }
        mK.idImgSl.setOnClick(javaClass.simpleName) {
            mK.idScrollView.fullScroll(ScrollView.FOCUS_DOWN)
        }
        val netspp = NetworkSpeed()
        //  netspp.startMoritor()
        MainScope().launch(Dispatchers.IO) {
            netspp.startMoritor()
        }
        lifecycleScope.launch(Dispatchers.Main) {
            launch {
                while (true) {
                    val percent = BatteryReceiver.level / BatteryReceiver.scale.toFloat()
                    mK.idDcDl.text = "${(percent * 100).toInt()}%"
                    delay(10000)
                }
            }
            launch {
                while (true) {
                    mK.idTvUploadSize.text = netspp.totalTxSpeed.toFormatSize()
                    mK.idTvDownloadSize.text = netspp.totalRxSpeed.toFormatSize()
                    delay(4000)
                }
            }
            launch {
                while (true) {
                    val ron = Random.nextInt(0, 100)
                    mK.idNetworkDownload.isVisible = ron >= 30
                    mK.idNetworkUpload.isVisible = ron < 30
                    delay(4000)
                }
            }

        }

    }



    fun saveDian(key: String) {
        lifecycleScope.launch {
            val value = requireContext().queryDataStoreBlock(booleanPreferencesKey(key), false)
            if (!value) {
                requireContext().saveDataStore(booleanPreferencesKey(key), true)
            }
        }
    }

    override fun onPause() {
        super.onPause()

    }

    override fun onResume() {
        super.onResume()
        initStorage()
        lifecycleScope.launch {
            if (requireContext().queryDataStoreBlock(booleanPreferencesKey("dianJunk"), false)) {
                mK.dianJunk.visibility = View.GONE
            }
            if (requireContext().queryDataStoreBlock(
                    booleanPreferencesKey("dianAntivirus"),
                    false
                )
            ) {
                mK.dianAntivirus.visibility = View.GONE
            }
            if (requireContext().queryDataStoreBlock(
                    booleanPreferencesKey("dianRecentApp"),
                    false
                )
            ) {
                mK.dianRecentApp.visibility = View.GONE
            }
            if (requireContext().queryDataStoreBlock(
                    booleanPreferencesKey("dianAppManager"),
                    false
                )
            ) {
                mK.dianAppManager.visibility = View.GONE
            }
            if (requireContext().queryDataStoreBlock(
                    booleanPreferencesKey("dianNetworkTraffic"),
                    false
                )
            ) {
                mK.dianNetworkTraffic.visibility = View.GONE
            }
            if (requireContext().queryDataStoreBlock(
                    booleanPreferencesKey("dianBatteryInfo"),
                    false
                )
            ) {
                mK.dianBatteryInfo.visibility = View.GONE
            }
        }
    }

    @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
        mK.idTvOccupied.text = "${usedSize.toFormatSize()}/ ${totalSize.toFormatSize()}"
    }


    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
    }


    var totalsize = 0L
    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
    }


}
