package com.zxhyis.toolss.base

import android.app.AppOpsManager
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.PermissionUtils
import com.zxhyis.toolss.ad.EventHelper
import com.zxhyis.toolss.logic.ActivityCollector
import com.zxhyis.toolss.ui.home.MainActivity


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

    lateinit var vb: T

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ActivityCollector.addActivity(this)
        vb = getViewBinding1()
        setContentView(vb.root)
        init()
        EventHelper.event("page_${javaClass.simpleName}")
    }

    abstract fun getViewBinding1(): T

    abstract fun init()

    companion object {
        private var requestPermissionCount = 3
    }

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

    open fun onPermissionsResult(isGranted: Boolean) {}
    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 || requestPermissionCount <= 0) {
                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 {
                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)
//                DialogViews.showGerPermisson(this,{
//
//                },{
//
//                })
            }

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

    override fun onDestroy() {
        super.onDestroy()
        ActivityCollector.removeActivity(this)
    }

    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) {}
}

