package com.zxhyis.toolss.ui.page.applock

import android.annotation.SuppressLint
import android.app.AppOpsManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.SPUtils
import com.github.ihsg.patternlocker.OnPatternChangeListener
import com.github.ihsg.patternlocker.PatternLockerView
import com.zxhyis.toolss.R
import com.zxhyis.toolss.ad.ConfigHelper
import com.zxhyis.toolss.base.TopActivity
import com.zxhyis.toolss.databinding.ActivityLayoutLockManagerBinding
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.ui.dialog.DialogViews
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

class AppLockManagerActivity : TopActivity<ActivityLayoutLockManagerBinding>() {
    override fun getViewBinding1(): ActivityLayoutLockManagerBinding {
        return ActivityLayoutLockManagerBinding.inflate(layoutInflater)
    }

    private val appList = mutableListOf<AppBean>()
    override fun onStart() {
        super.onStart()
        if (ConfigHelper.ifAppLock) {
            val appOpsManager = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                if (appOpsManager.unsafeCheckOpNoThrow(
                        AppOpsManager.OPSTR_GET_USAGE_STATS,
                        android.os.Process.myUid(),
                        this.packageName
                    ) != AppOpsManager.MODE_ALLOWED
                ) {
                    DialogViews.showLastStep(this) {
                        Log.e("MXL", "弹窗回到: ")
                        checkAccesSettings(true)
                    }
                }
            } else {
                if (appOpsManager.checkOpNoThrow(
                        AppOpsManager.OPSTR_GET_USAGE_STATS,
                        android.os.Process.myUid(),
                        this.packageName
                    ) != AppOpsManager.MODE_ALLOWED
                ) {
                    DialogViews.showLastStep(this) {
                        Log.e("MXL", "弹窗回到: ")
                        checkAccesSettings(true)
                    }
                }
            }
        }

    }

    override fun onAccesSettingsResult(isGranted: Boolean) {
        if (isGranted) {

        } else {
            Log.e("MXL", "onAccesSettingsResult: " + ConfigHelper.ifAppLock)
            if (ConfigHelper.ifAppLock) {

            }

        }
    }

    override fun init() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        vb.root.updatePadding(top = BarUtils.getStatusBarHeight())
        if (ConfigHelper.appList.isNullOrEmpty()) {
            MainScope().launch(Dispatchers.Main) {
                launch(Dispatchers.IO) {
                    ConfigHelper.appList = AppUtils.getAppsInfo().shuffled()
                }
                ConfigHelper.appList?.filter { !it.isSystem }?.forEach {
                    val bean = AppBean(it.icon, it.packageName, it.name, false)
                    appList.add(bean)
                    val memoryApps = SPUtils.getInstance().getStringSet("lockApps", mutableSetOf())
                    appList.forEach { a ->
                        memoryApps.forEach {
                            if (a.packname == it) {
                                Log.e("MXL", "init: " + it.toString())
                                a.isSelect = true
                            }
                        }
                    }
                    appList.sortByDescending { it.isSelect }
                    vb.idAppRl.run {
                        layoutManager = LinearLayoutManager(context)
                        adapter = mAdapter
                    }
                }
            }
        } else {
            MainScope().launch(Dispatchers.IO) {
                ConfigHelper.appList?.filter { !it.isSystem }?.forEach { it ->
                    val bean = AppBean(it.icon, it.packageName, it.name, false)
                    appList.add(bean)
                    val memoryApps = SPUtils.getInstance().getStringSet("lockApps", mutableSetOf())
                    appList.forEach { a ->
                        memoryApps.forEach {
                            if (a.packname == it) {
                                Log.e("MXL", "init: " + it.toString())
                                a.isSelect = true
                            }
                        }
                    }
                    appList.sortByDescending { it.isSelect }
                    //  lockDao?.insert(bean)
                    vb.idAppRl.run {
                        layoutManager = LinearLayoutManager(context)
                        adapter = mAdapter
                    }
                    updateBottomView()
                }
            }
//            lockDao?.getAll()?.observe(this@AppLockManagerActivity) {
//                appList.clear()
//                appList.addAll(it)
//
//            }
        }
        vb.idBackLockManager.setOnClick(javaClass.simpleName) {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                finishToMain()
            }
        })
        vb.idEnable.setOnClick(javaClass.simpleName) {
            vb.idLlNoEnable.isVisible = false
            vb.idDrawPattern.isVisible = true
            startService(Intent(this, ProtectorService::class.java))
        }
        vb.idOneView.setOnPatternChangedListener(object : OnPatternChangeListener {
            override fun onChange(view: PatternLockerView, hitIndexList: List<Int>) {

            }

            override fun onClear(view: PatternLockerView) {

            }

            override fun onComplete(view: PatternLockerView, hitIndexList: List<Int>) {
                Log.e("MXL", "onComplete: "+hitIndexList )
                val isOk = isPatternOk(hitIndexList)
                view.updateStatus(!isOk)

                // ConfigHelper.ifAppLock = true
            }

            override fun onStart(view: PatternLockerView) {

            }

        })
    }
    private fun isPatternOk(hitIndexList: List<Int>): Boolean {
        PatternHelper().validateForSetting(hitIndexList)
        return PatternHelper().isOk
    }

    private val mAdapter by lazy {
        class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val ivImage: ImageView
            val tvName: TextView?
            val ivLock: ImageView

            init {
                ivImage = view.findViewById(R.id.id_app_icon)
                tvName = view.findViewById(R.id.id_tv_name)
                ivLock = view.findViewById(R.id.id_img_lock)
            }
        }

        object : RecyclerView.Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                val view = LayoutInflater.from(this@AppLockManagerActivity).inflate(
                    R.layout.item_layout_lock_manager, parent, false
                )
                return ViewHolder(view)
            }

            override fun getItemCount() = appList.size

            @SuppressLint("RecyclerView")
            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                val item = appList[position]
//                val c = ConfigHelper.appList?.firstOrNull {
//                    it.packageName == item.packname
//                }

                holder.ivImage.setImageDrawable(item.drawable)
                holder.tvName?.text = item.name
                if (item.isSelect) {
                    holder.ivLock.setImageResource(R.drawable.suo_s)
                } else {
                    holder.ivLock.setImageResource(R.drawable.suo_n)
                }
                holder.itemView.setOnClickListener {
                    item.isSelect = !item.isSelect
                    Log.e("MXL", "onBindViewHolder: " + item.isSelect)
                    if (item.isSelect) {
                        Log.e("MXL", "选中给加到sp里: ")
                        val stringSet =
                            SPUtils.getInstance().getStringSet("lockApps", mutableSetOf())
                        stringSet.add(item.packname)
                        SPUtils.getInstance().put("lockApps", stringSet)
                    } else {
                        Log.e("MXL", "取消选中，移除出去: ")
                        val stringSet =
                            SPUtils.getInstance().getStringSet("lockApps", mutableSetOf())
                        stringSet.remove(item.packname)
                        SPUtils.getInstance().put("lockApps", stringSet)
                        Log.e(
                            "MXL",
                            "onBindViewHolder: " + (SPUtils.getInstance()
                                .getStringSet("lockApps", mutableSetOf<String?>()).toString())
                        )

                    }
                    notifyItemChanged(position, 1)
                    updateBottomView()

                    //  notifyItemRangeChanged(0, appList.size, 1)
                }


            }

            override fun onBindViewHolder(
                holder: ViewHolder,
                position: Int,
                payloads: MutableList<Any>
            ) {
                super.onBindViewHolder(holder, position, payloads)
                val item = appList[position]
                if (item.isSelect) {
                    holder.ivLock.setImageResource(R.drawable.suo_s)
                } else {
                    holder.ivLock.setImageResource(R.drawable.suo_n)
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateBottomView() {
        val currtentApps = SPUtils.getInstance().getStringSet("lockApps", mutableSetOf())
        vb.idEnable.text = "ENABLE(${currtentApps.size})"
    }
}