package pxds.lmmd.zmwf

import android.app.AppOpsManager
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.PermissionUtils
import com.test.basd.supercleanermax.R
import org.json.JSONObject
import pxds.dlpf.buoz.fico.Ohyk
import pxds.etmo.Mzvb
import pxds.etmo.Padb
import pxds.lmmd.zmwf.Khko.string

abstract class Bpfw<T : ViewBinding> : AppCompatActivity() {

    var dialog: Dialog? = null

    private val accessLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {

        }

    private var isRequestedAccess = false

    private var isRequested = false

    private val permissionLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                onPermissionsResult(Environment.isExternalStorageManager())
            }
        }

    protected open val isLightMode: Boolean? = null

    protected abstract val binding: T

    fun checkAccesSettings(needcheck: Boolean = false) {
        val appOpsManager = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
        if (needcheck) {
            onAccesSettingsResult(
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    appOpsManager.unsafeCheckOpNoThrow(
                        AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), this.packageName
                    ) == AppOpsManager.MODE_ALLOWED
                } else {
                    appOpsManager.checkOpNoThrow(
                        AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), this.packageName
                    ) == AppOpsManager.MODE_ALLOWED
                }
            )
        } else {
            if (isRequestedAccess) {
                onAccesSettingsResult(
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        appOpsManager.unsafeCheckOpNoThrow(
                            AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), this.packageName
                        ) == AppOpsManager.MODE_ALLOWED
                    } else {
                        appOpsManager.checkOpNoThrow(
                            AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), this.packageName
                        ) == AppOpsManager.MODE_ALLOWED
                    }
                )
                return
            }
            isRequestedAccess = true
        }
        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
            ) {
                onAccesSettingsResult(true)
            } else {
                val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
                intent.addCategory(R.string.ޛޠޓޑޥ_D.string())
                intent.data = Uri.parse(R.string.ޙތޛޥބ_D.string((this.packageName).toString()))
                accessLauncher.launch(intent)
            }

        } else {
            if (appOpsManager.checkOpNoThrow(
                    AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), this.packageName
                ) == AppOpsManager.MODE_ALLOWED
            ) {
                onAccesSettingsResult(true)
            } else {
                val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
                intent.addCategory(R.string.ޛޠޓޑޥ_D.string())
                intent.data = Uri.parse(R.string.ޙތޛޥބ_D.string((this.packageName).toString()))
                accessLauncher.launch(intent)
            }
        }

    }

    protected abstract fun initView()

    override fun onDestroy() {
        super.onDestroy()
        if (dialog != null) {
            dialog?.dismiss()
        }
    }

    protected open fun initListener() {}

    fun checkPermission(needcheck: Boolean = false) {
        if (needcheck) {
            onPermissionsResult(
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    Environment.isExternalStorageManager()
                } else {
                    PermissionUtils.isGranted(PermissionConstants.STORAGE)
                }
            )
        } else {
            if (isRequested) {
                onPermissionsResult(
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        Environment.isExternalStorageManager()
                    } else {
                        PermissionUtils.isGranted(PermissionConstants.STORAGE)
                    }
                )
                return
            }
            isRequested = true

        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                onPermissionsResult(true)
            } else {
                if (isFinishing || isDestroyed) {
                    return
                }
                dialog = Ohyk.showGerPermission(this, {

                    val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                    intent.addCategory(R.string.ޛޠޓޑޥ_D.string())
                    intent.data = Uri.parse(R.string.ޙތޛޥބ_D.string((packageName).toString()))
                    permissionLauncher.launch(intent)
                    Padb.launch(this)
                }, {
                    finishToMain()
                })
            }

        } else {
            PermissionUtils.permissionGroup(PermissionConstants.STORAGE)
                .callback { isAllGranted, _, _, _ ->
                    if (isAllGranted) {
                        onPermissionsResult(true)
                    } else {
                        onPermissionsResult(false)
                    }
                }.request()
        }
    }

    open fun onAccesSettingsResult(isGranted: Boolean) {
        val obj = JSONObject()
        obj.put(R.string.ޓޞޜޅމ_D.string(), javaClass.simpleName)
        if (isGranted) {
            Wspd.event(R.string.ޝގޗޜލ_D.string(), ext = obj)
        } else {
            Wspd.event(R.string.ޚޏހޔޞ_D.string(), ext = obj)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        isLightMode?.let {
            BarUtils.setStatusBarLightMode(this, it)
        }

        Wspd.event(R.string.ޟޝޙޡމ_D.string((javaClass.simpleName).toString()))

        initView()
        initListener()
    }

    open fun onPermissionsResult(isGranted: Boolean) {
        val obj = JSONObject()
        obj.put(R.string.ޓޞޜޅމ_D.string(), javaClass.simpleName)
        if (isGranted) {
            Wspd.event(R.string.ޝގޗޜލ_D.string(), ext = obj)
        } else {
            Wspd.event(R.string.ޚޏހޔޞ_D.string(), ext = obj)
        }
    }

    protected fun finishToMain() {
        if (this !is Mzvb && !ActivityUtils.isActivityExistsInStack(Mzvb::class.java)) {
            startActivity(Intent(this, Mzvb::class.java))
        }
        finish()
    }
}