package com.zxhyis.toolss.ui.page.recentusage

import android.app.usage.UsageEvents
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import androidx.activity.addCallback
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.blankj.utilcode.util.ActivityUtils
import com.google.android.material.tabs.TabLayoutMediator
import com.zxhyis.toolss.R
import com.zxhyis.toolss.ad.AdmobUtils
import com.zxhyis.toolss.ad.EventHelper
import com.zxhyis.toolss.databinding.ActivityRecentAppBinding
import com.zxhyis.toolss.logic.ActivityLauncher
import com.zxhyis.toolss.logic.AppBean
import com.zxhyis.toolss.logic.LogEx
import com.zxhyis.toolss.logic.ReportInterface
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.logic.utils.TestN
import com.zxhyis.toolss.ui.home.MainActivity
import com.zxhyis.toolss.ui.page.appmanager.UsageAccessSettings.checkUsageAccessSettings
import com.zxhyis.toolss.ui.page.viewmodel.AppViewModel
import com.zxhyis.toolss.ui.page.viewmodel.AppViewModel.Companion.TODAY_QUERY
import com.zxhyis.toolss.ui.page.viewmodel.AppViewModel.Companion.timePair
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class RecentAppActivity : AppCompatActivity(), ReportInterface {

    private val TAG = "RecentAppActivity"
    private lateinit var binding: ActivityRecentAppBinding
    private val pages = arrayListOf<Fragment>()
    private lateinit var pagerAdapter: ScreenSlidePagerAdapter
    private lateinit var tabs: Array<String>
    private var dataList = ArrayList<AppBean>()
    private val viewModel: AppViewModel by viewModels()
    private lateinit var context: Context
    private lateinit var launcher: ActivityLauncher

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        launcher = ActivityLauncher(this)
        context = this
        binding = ActivityRecentAppBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initView()

        if (checkUsageAccessSettings()) {
            Log.e("MXL", "onCreate: " + checkUsageAccessSettings())
            intData()
            playlottie()
        } else {
            binding.llContent.visibility = View.GONE
            binding.flPermission.visibility = View.VISIBLE
            binding.tvGrand.setOnClick(javaClass.simpleName) {
                val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
                intent.addCategory("android.intent.category.DEFAULT")
                intent.data = Uri.parse("package:${context.packageName}")
                launcher.launch(intent) {
                    LogEx.logDebug(TAG, "launcher callback")
                    if (checkUsageAccessSettings()) {
                        binding.flPermission.visibility = View.GONE
                        binding.llContent.visibility = View.VISIBLE
                        intData()
                    } else {
                        finishToMain()
                    }
                }
            }
        }
        pageReport()
    }

    private fun playlottie(showFinish: (() -> Unit)? = null) {
        binding.llLottie.isVisible = true
        binding.lottie.imageAssetsFolder = "recentapp/images/"
        binding.lottie.setAnimation("recentapp/data.json")
        binding.lottie.playAnimation()
        binding.root.postDelayed({
            AdmobUtils.showInterstitialAd(this) {
                binding.llLottie.isVisible = false
                showFinish?.invoke()
            }
        }, 6000)
    }

    fun initView() {
        initPage()
        intTab()
        binding.flBack.setOnClick(javaClass.simpleName) {
            AdmobUtils.showInterstitialAd(this) {
                finish()
            }
        }
        onBackPressedDispatcher.addCallback {
            LogEx.logDebug(TAG, "onBackPressedDispatcher")
            AdmobUtils.showInterstitialAd(this@RecentAppActivity) {
                finish()
            }
        }
    }


    private fun intData() {


        CoroutineScope(Dispatchers.IO).launch {

            //测试打印数据
//            printEventList(context, lifecycleScope).await()

            //构建AppData列表
            initAppData()

            //设置启动数据
            setLaunchesData()

            //屏幕时间数据
            setScreenTimeData()

            //更新UI数据
            launch(Dispatchers.Main) {
                updateFragmentData(0, 1)
            }
        }
    }

    private fun initAppData() {
        dataList.clear()

        val pm = packageManager
        val packages = pm.getInstalledPackages(0)

        packages.forEach { app ->
            if (viewModel.isLaunchApp(context, app)) {

                val appBean = AppBean(
                    app.applicationInfo.loadIcon(pm),
                    app.applicationInfo.loadLabel(pm).toString(),
                    app.applicationInfo.packageName,
                    false
                )

                //安装时间
                viewModel.setAppInstallTime(appBean, context)
                dataList.add(appBean)
            }
        }

    }

    private fun updateFragmentData(vararg position: Int) {
        if (position.contains(0)) {
            val launchesFragment = pages[0] as LaunchesFragment
            launchesFragment.setAppUseData(dataList)
        }

        if (position.contains(1)) {
            val screenTimeFragment = pages[1] as ScreenTimeFragment
            screenTimeFragment.setScreenData(dataList)
        }

    }

    private fun setScreenTimeData(queryTime: Int = TODAY_QUERY) {
        val pair = timePair(queryTime)

        val screenTimeMap = ScreenTimeStat(pair.first, pair.second).run(context)
        //key=com.vivo.appfilter pkg=com.vivo.appfilter f30766a=防拉起服务 f30767b=com.vivo.appfilter c=1132
        dataList.forEach { app ->
            if (screenTimeMap.keys.contains(app.pkg)) {
                val value = screenTimeMap[app.pkg]
                value?.let { b ->
                    app.screenTime = b.c
                }
            }
        }
    }

    private fun setLaunchesData(queryTime: Int = TODAY_QUERY) {
        val tempList = arrayListOf<AppBean>()
        tempList.addAll(dataList)

        //后台启动数据
        dataList = viewModel.getAppUseAnalyze(context, queryTime, tempList)

        //前台启动数据
        val pair = timePair(queryTime)
        val ast = TestN(pair.first, pair.second)
        val hashMap = ast.run(context)
        dataList.forEach { app ->
            if (hashMap.keys.contains(app.pkg)) {
                val value = hashMap[app.pkg]
                if (value != null) {
                    val tempList2 = arrayListOf<UsageEvents.Event>()
                    tempList2.addAll(value)
                    app.usageEvents?.also { evens -> tempList2.addAll(evens) }
                    app.usageEvents = tempList2
                }
            }
        }
    }

    fun changeTimeRefresh(queryTime: Int, fragmentPosition: Int) {
        lifecycleScope.launch(Dispatchers.IO) {
            initAppData()

            //设置启动数据
            setLaunchesData(queryTime)

            //屏幕时间数据
            setScreenTimeData(queryTime)

            //更新UI数据
            launch(Dispatchers.Main) { updateFragmentData(fragmentPosition) }
        }
    }


    private fun intTab() {
        //有个问题结合ViewPager2就无法用静态xml中的TabItem
        tabs = arrayOf(
            resources.getString(R.string.launches),
            resources.getString(R.string.screen_time),
        )
        TabLayoutMediator(binding.tabLayout, binding.viewpager2) { tab, position ->
            tab.text = tabs[position]
            binding.viewpager2.currentItem = position
        }.attach()

        binding.viewpager2.currentItem = 0
    }

    private fun initPage() {
        pages.add(LaunchesFragment())
        pages.add(ScreenTimeFragment())
        pagerAdapter = ScreenSlidePagerAdapter(this)
        binding.viewpager2.adapter = pagerAdapter
    }

    inner class ScreenSlidePagerAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) {
        override fun getItemCount(): Int = pages.size
        override fun createFragment(position: Int): Fragment = pages[position]
    }

    override fun pageReport() {
        EventHelper.event("page_${javaClass.simpleName}")
    }

    fun finishToMain() {
        if (!ActivityUtils.isActivityExistsInStack(MainActivity::class.java)) {
            startActivity(Intent(this, MainActivity::class.java))
        }
        finish()
    }

}