package com.zxhyis.toolss.ui.page


import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.graphics.Color
import android.net.Uri
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import com.zxhyis.toolss.R
import com.zxhyis.toolss.ad.AdmobUtils
import com.zxhyis.toolss.base.TopActivity
import com.zxhyis.toolss.databinding.ActivityAppManagerBinding
import com.zxhyis.toolss.logic.AppBean
import com.zxhyis.toolss.logic.Logic
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.logic.showToast
import com.zxhyis.toolss.ui.adapter.AppAdapter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class AppManagerActivity : TopActivity<ActivityAppManagerBinding>() {

    private lateinit var appAdapter: AppAdapter
    private val dataList = ArrayList<AppBean>()
    private val result =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            updateBt()
        }

    override fun getViewBinding1(): ActivityAppManagerBinding {
        return ActivityAppManagerBinding.inflate(layoutInflater)
    }

    override fun init() {
        vb.inApp.tvTitle.text = getString(R.string.app_manager)
        vb.lvScan.playAnimation()

        vb.inApp.ivBack.setOnClick(javaClass.simpleName) {
            onBackPressedDispatcher.onBackPressed()
        }

        vb.btUninstall.setOnClick(javaClass.simpleName) {
            if (isCanUninstall()) {
                uninstallApp()
            } else {
                "Please choose one at least".showToast()
            }
        }

        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (!vb.lvScan.isAnimating) {
                    finishToMain()
                }
            }
        })
        vb.lvScan.addAnimatorListener(object : AnimatorListener {
            override fun onAnimationStart(animation: Animator) {

            }

            override fun onAnimationEnd(animation: Animator) {
                AdmobUtils.showInterstitialAd(this@AppManagerActivity){
                    vb.clsApp.setBackgroundColor(Color.WHITE)
                    vb.lvScan.visibility = View.GONE
                    vb.appScan.visibility = View.GONE
                    vb.rvDelete.visibility = View.VISIBLE
                    vb.btUninstall.visibility = View.VISIBLE
                }
//                MaxAdUtils.showMaxInterstitialAd(this@AppManagerActivity,"interstitial_slot"){
//
//                }

            }

            override fun onAnimationCancel(animation: Animator) {

            }

            override fun onAnimationRepeat(animation: Animator) {

            }

        })


    }

    private fun initRv() {
        CoroutineScope(Dispatchers.IO).launch {
            delay(500)
            val pm = packageManager
            val packages = pm.getInstalledPackages(0)
            for (app in packages) {
                if ((app.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM) < 1 && app.applicationInfo.packageName != packageName) {
                    dataList.add(
                        AppBean(
                            app.applicationInfo.loadIcon(pm),
                            app.applicationInfo.loadLabel(pm).toString(),
                            app.applicationInfo.packageName,
                            false
                        )
                    )
                }
            }

            appAdapter = AppAdapter(dataList, object : Logic {
                override fun doLogic() {
                    updateBt()
                }

            })

            launch(Dispatchers.Main) {
                vb.rvDelete.apply {
                    layoutManager = LinearLayoutManager(this@AppManagerActivity)
                    adapter = appAdapter
                }
            }
        }


    }

    private fun updateBt() {
        if (isCanUninstall()) {
            vb.btUninstall.setBackgroundResource(R.drawable.bg_shape_set)
        } else {
            vb.btUninstall.setBackgroundResource(R.drawable.bg_shape_delete_no)
        }
    }

    private fun isCanUninstall(): Boolean {
        for (app in dataList) {
            if (app.isSelected) {
                return true
            }
        }
        return false
    }

    private fun uninstallApp() {
        for (app in dataList) {
            if (app.isSelected) {
                val intent = Intent(Intent.ACTION_DELETE, Uri.parse("package:${app.pkg}"))
                result.launch(intent)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        dataList.clear()
        initRv()
    }

    override fun onDestroy() {
        super.onDestroy()
        dataList.clear()
    }


}