package com.base.browserwhite.ui.activity

import android.app.usage.StorageStatsManager
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.os.storage.StorageManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.base.browserwhite.R
import com.base.browserwhite.bean.ConstObject.isFirstMainShow
import com.base.browserwhite.bean.ConstObject.mainShowCount
import com.base.browserwhite.bean.ConstObject.shortcutShowSp
import com.base.browserwhite.databinding.ActivityMainBinding
import com.base.browserwhite.ui.activity.splash.Splash2Activity
import com.base.browserwhite.ui.fragment.FileFragment
import com.base.browserwhite.ui.fragment.HomeFragment
import com.base.browserwhite.ui.views.DialogViews.showDefaultBrowserDialog
import com.base.browserwhite.ui.views.DialogViews.showMyAccountDialog
import com.base.browserwhite.ui.views.PermissionDialog.showPermissionBottomSheet
import com.base.browserwhite.ui.views.RateDialog.showRateDialog
import com.base.browserwhite.ui.widget.BrowserAppWidget
import com.base.browserwhite.utils.AppPreferences
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.utils.ShortcutUtils
import com.base.browserwhite.utils.ShortcutUtils.addDeskShortCut
import java.io.File


class MainActivity : BaseActivity<ActivityMainBinding>() {

    private val TAG = "MainActivity"

    private val homeFragment: HomeFragment by lazy {
        HomeFragment()
    }
    private val fileFragment: FileFragment by lazy {
        FileFragment()
    }

    override val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }
    var usedBytes: Long = 0
    var totalBytes: Long = 0

    private val fragments by lazy {
        mutableListOf(homeFragment, fileFragment)
    }

    var showPermissionDialog: Boolean = false
    override fun initView() {

        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        binding.viewPager2.run {
            isUserInputEnabled = false
            adapter = object : FragmentStateAdapter(this@MainActivity) {
                override fun getItemCount(): Int {
                    return fragments.size
                }

                override fun createFragment(position: Int): Fragment {
                    return fragments[position]
                }
            }
        }

        binding.viewPager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
            }
        })

        if (isFirstMainShow) {
            showDefaultBrowserDialog(launcher)
        }



        if (intent.extras?.getBoolean("cleanAskPermission", false) == true) {
            showPermissionDialog = true
            showPermissionBottomSheet(launcher) {}
        }

        BrowserAppWidget.updateAllWidget(this)

        addDeskShortCut()

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        homeFragment.onActivityResult(resultCode, resultCode, data)
    }

    override fun initListener() {
        super.initListener()
        binding.llHome.setOnClickListener {
            disSelect()
            binding.llHome.isSelected = true
            binding.viewPager2.setCurrentItem(0, false)
        }
        binding.llFile.setOnClickListener {
            disSelect()
            binding.llFile.isSelected = true
            binding.viewPager2.setCurrentItem(1, false)
        }

        binding.llHome.callOnClick()

        binding.llMy.setOnClickListener {
            showMyAccountDialog(launcher)
        }
    }


    private fun disSelect() {
        binding.llHome.isSelected = false
        binding.llFile.isSelected = false
    }


    var rateShow: Boolean = false
    override fun onResume() {
        super.onResume()
        showStorage()
        mainShowCount++

        LogEx.logDebug(TAG, "mainShowCount=$mainShowCount showPermissionDialog=$showPermissionDialog")

        if (mainShowCount >= 2 && !showPermissionDialog) {
            if (rateShow) {
                return
            }
            rateShow = true
            showRateDialog()
            intent.removeExtra("cleanAskPermission")
        }

        val isRated = AppPreferences.getInstance().getBoolean("isRated", false)
        if (mainShowCount >= 3 && !showPermissionDialog && !shortcutShowSp && isRated) {
            shortcutShowSp = true
            val appName = this.resources.getString(R.string.app_name)
            // 在Activity中调用创建快捷方式的方法
            ShortcutUtils.requestCreateShortcut(
                this, "my_shortcut_id", appName, appName,
                Splash2Activity::class.java, R.mipmap.logo
            )
            intent.removeExtra("cleanAskPermission")
            return
        }

    }

    private fun showStorage() {

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

            Thread {
                totalBytes = storageStatsManager.getTotalBytes(StorageManager.UUID_DEFAULT)
                usedBytes = totalBytes - storageStatsManager.getFreeBytes(StorageManager.UUID_DEFAULT)
            }.start()

        } else {
            val path1: File = Environment.getDataDirectory()
            val stat1 = StatFs(path1.path)
            val path2: File = Environment.getExternalStorageDirectory()
            val stat2 = StatFs(path2.path)
            totalBytes = (stat1.totalBytes + stat2.totalBytes)
            usedBytes = ((stat1.totalBytes + stat2.totalBytes) - (stat1.availableBytes + stat2.availableBytes))
        }
    }


}