package com.test.basd.smartjunkcleaner.helps

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.smartjunkcleaner.activity.MainActivity
import com.test.basd.smartjunkcleaner.activity.PermissionTripActivity
import com.test.basd.smartjunkcleaner.view.DialogViews
import org.json.JSONObject

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

    protected abstract val binding: T

    protected open val isLightMode: Boolean? = null

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

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

        initView()
        initListener()
    }

    protected abstract fun initView()

    protected open fun initListener() {}


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

    open fun onPermissionsResult(isGranted: Boolean) {
        val obj = JSONObject()
        obj.put("activity", javaClass.simpleName)
        if (isGranted) {
            EventHelper.event("permission_allow", ext = obj)
        } else {
            EventHelper.event("permission_deny", ext = obj)
        }
    }

    private var isRequested = false
    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
            //  requestPermissionCount--
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                onPermissionsResult(true)
            } else {
                if (isFinishing || isDestroyed) {
                    return
                }
                dialog = DialogViews.showGerPermission(this, {

                    val intent =
                        Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                    intent.addCategory("android.intent.category.DEFAULT")
                    intent.data = Uri.parse("package:${packageName}")
                    permissionLauncher.launch(intent)
                    PermissionTripActivity.launch(this)
                }, {
                    finishToMain()
                })
            }

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

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

    private var isRequestedAccess = false

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

        }

    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("android.intent.category.DEFAULT")
                intent.data = Uri.parse("package:${this.packageName}")
                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("android.intent.category.DEFAULT")
                intent.data = Uri.parse("package:${this.packageName}")
                accessLauncher.launch(intent)
            }
        }


    }

    open fun onAccesSettingsResult(isGranted: Boolean) {
        val obj = JSONObject()
        obj.put("activity", javaClass.simpleName)
        if (isGranted) {
            EventHelper.event("permission_allow", ext = obj)
        } else {
            EventHelper.event("permission_deny", ext = obj)
        }
    }

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