package com.test.basd.supercleanermax.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.PackageManager.NameNotFoundException
import android.net.Uri
import android.provider.Settings
import android.view.View
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.test.basd.supercleanermax.R
import com.test.basd.supercleanermax.adapter.PermissionAdapter
import com.test.basd.supercleanermax.bean.AppBean
import com.test.basd.supercleanermax.bean.PermissionBean
import com.test.basd.supercleanermax.bean.PermissionBean.Companion.setDesc
import com.test.basd.supercleanermax.bean.PermissionBean.Companion.setTittle
import com.test.basd.supercleanermax.databinding.ActivityPermissionManagerBinding
import com.test.basd.supercleanermax.helps.BaseActivity
import com.test.basd.supercleanermax.helps.LogEx
import com.test.basd.supercleanermax.view.PermissionFilterDialog.showPermissionFilterDialog

class PermissionManagerActivity : BaseActivity<ActivityPermissionManagerBinding>() {
    override val isLightMode = true
    private val TAG = "PermissionManagerActivity"
    private var appBean: AppBean? = null
    private val appNormalPermissions = arrayListOf<PermissionBean>()
    private val appSensitivePermissions = arrayListOf<PermissionBean>()
    private lateinit var normalAdapter: PermissionAdapter
    private lateinit var sensitiveAdapter: PermissionAdapter
    private var normalExpand = true
    private var sensitiveExpand = true
    private var isAllPermission = true//是否所有权限

    override val binding: ActivityPermissionManagerBinding by lazy {
        ActivityPermissionManagerBinding.inflate(layoutInflater)
    }


    override fun initView() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        val json = intent.extras?.getString("AppBean")
        LogEx.logDebug(TAG, "json=$json")
        appBean = json?.let { AppBean.appBeanGson.fromJson(it, AppBean::class.java) }
        LogEx.logDebug(TAG, "appBean=$appBean")

        appBean?.apply {
            val applicationInfo = packageManager.getApplicationInfo(this.pkg, PackageManager.GET_META_DATA)
            binding.ivIcon.setImageDrawable(packageManager.getApplicationIcon(applicationInfo))
            binding.tvName.text = this.appName
            getAppPermissions(this.pkg)
        }
    }

    override fun initListener() {
        binding.flBack.setOnClickListener {
            finish()
        }
        binding.tvAdministration.setOnClickListener {
            val intent = Intent()
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            intent.setData(Uri.parse("package:" + appBean?.pkg))
            startActivity(intent)
        }
        binding.llNormal.setOnClickListener {
            normalExpand = !normalExpand
            setExpandCollapseNormal()
        }
        binding.llSensitive.setOnClickListener {
            sensitiveExpand = !sensitiveExpand
            setExpandCollapseSensitive()
        }
        binding.flFilter.setOnClickListener {
            showPermissionFilterDialog(
                allClick = {
                    if (!isAllPermission) {
                        changeAllPermission()
                        normalExpand = true
                        setExpandCollapseNormal()
                    }
                    isAllPermission = true
                },
                authorizedClick = {
                    if (isAllPermission) {
                        changeOnlyAuthorized()
                        sensitiveExpand = true
                        setExpandCollapseSensitive()
                    }
                    isAllPermission = false
                }
            )
        }
    }

    private fun changeOnlyAuthorized() {
        val list1 = appNormalPermissions.filter { it.isAuthorized }
        normalAdapter.setData(list1)
        binding.tvNormalNumber.text = list1.size.toString()

        val list2 = appSensitivePermissions.filter { it.isAuthorized }
        sensitiveAdapter.setData(list2)
        binding.tvSensitiveNumber.text = list2.size.toString()
    }

    private fun changeAllPermission() {
        normalAdapter.setData(appNormalPermissions)
        binding.tvNormalNumber.text = appNormalPermissions.size.toString()

        sensitiveAdapter.setData(appSensitivePermissions)
        binding.tvSensitiveNumber.text = appSensitivePermissions.size.toString()
    }

    @SuppressLint("StringFormatMatches", "SetTextI18n")
    private fun getAppPermissions(pkg: String) {
        val pm = this.packageManager
        val info: PackageInfo
        try {
            info = pm.getPackageInfo(pkg, PackageManager.GET_PERMISSIONS)
            val packagePermissions = info.requestedPermissions
            packagePermissions.forEach { permission ->
                LogEx.logDebug(TAG, "permission=$permission")
                val common = commonPermissions.find { it.permissionMatch == permission }
                common?.let {
                    val ss = pm.checkPermission(it.permissionMatch, pkg) == PackageManager.PERMISSION_GRANTED
                    if (it.permissionMatch == Manifest.permission.INTERNET) {
                        LogEx.logDebug(TAG, "ss=$ss")
                    }
                    it.isAuthorized = ss
                    appNormalPermissions.add(it)
                }


                val sensitive = sensitivePermissions.find { it.permissionMatch == permission }
                sensitive?.let {
                    it.isAuthorized = pm.checkPermission(it.permissionMatch, pkg) == PackageManager.PERMISSION_GRANTED
                    appSensitivePermissions.add(it)
                }

            }

        } catch (e: NameNotFoundException) {
            e.printStackTrace()
        }

        binding.tvDesc.text = "${appSensitivePermissions.size} Sensitive permissions"
        appNormalPermissions.forEach {
            it.setTittle()
            it.setDesc()
        }
        sensitivePermissions.forEach {
            it.setTittle()
            it.setDesc()
        }
        binding.tvNormalNumber.text = appNormalPermissions.size.toString()
        binding.tvSensitiveNumber.text = appSensitivePermissions.size.toString()
        intiRv()
    }

    private fun intiRv() {
        normalAdapter = PermissionAdapter()
        binding.rvNormal.adapter = normalAdapter
        normalAdapter.setData(appNormalPermissions)

        sensitiveAdapter = PermissionAdapter()
        binding.rvSensitive.adapter = sensitiveAdapter
        sensitiveAdapter.setData(appSensitivePermissions)

        setExpandCollapseSensitive()
        setExpandCollapseNormal()
    }

    private fun setExpandCollapseSensitive() {
        if (sensitiveExpand) {
            binding.ivArrowSensitive.setImageResource(R.mipmap.hxiala_s)
            binding.rvSensitive.visibility = View.VISIBLE
        } else {
            binding.ivArrowSensitive.setImageResource(R.mipmap.hxiala_x)
            binding.rvSensitive.visibility = View.GONE
        }
    }


    private fun setExpandCollapseNormal() {
        if (normalExpand) {
            binding.ivArrowNormal.setImageResource(R.mipmap.aa_xiala_s)
            binding.rvNormal.visibility = View.VISIBLE
        } else {
            binding.ivArrowNormal.setImageResource(R.mipmap.aa_xiala_x)
            binding.rvNormal.visibility = View.GONE
        }

    }


    companion object {
        @SuppressLint("InlinedApi")
        val commonPermissions = arrayListOf(
            PermissionBean(Manifest.permission.ACCESS_NETWORK_STATE),
            PermissionBean(Manifest.permission.ACCESS_WIFI_STATE),
            PermissionBean(Manifest.permission.BLUETOOTH),
            PermissionBean(Manifest.permission.BLUETOOTH_ADMIN),
            PermissionBean(Manifest.permission.BLUETOOTH_CONNECT),
            PermissionBean(Manifest.permission.BLUETOOTH_PRIVILEGED),
            PermissionBean(Manifest.permission.BLUETOOTH_SCAN),
            PermissionBean(Manifest.permission.CHANGE_NETWORK_STATE),
            PermissionBean(Manifest.permission.CHANGE_WIFI_STATE),
            PermissionBean(Manifest.permission.CONTROL_LOCATION_UPDATES),
            PermissionBean(Manifest.permission.DELETE_PACKAGES),
            PermissionBean(Manifest.permission.INSTALL_PACKAGES),
            PermissionBean(Manifest.permission.INTERNET),
            PermissionBean(Manifest.permission.MANAGE_EXTERNAL_STORAGE),
            PermissionBean(Manifest.permission.MANAGE_MEDIA),
            PermissionBean(Manifest.permission.MANAGE_WIFI_NETWORK_SELECTION),
            PermissionBean(Manifest.permission.MODIFY_AUDIO_SETTINGS),
            PermissionBean(Manifest.permission.NFC),
            PermissionBean(Manifest.permission.READ_EXTERNAL_STORAGE),
            PermissionBean(Manifest.permission.READ_MEDIA_AUDIO),
            PermissionBean(Manifest.permission.READ_MEDIA_IMAGES),
            PermissionBean(Manifest.permission.READ_MEDIA_VIDEO),
            PermissionBean(Manifest.permission.READ_SYNC_SETTINGS),
            PermissionBean(Manifest.permission.READ_SYNC_STATS),
            PermissionBean(Manifest.permission.REQUEST_DELETE_PACKAGES),
            PermissionBean(Manifest.permission.UPDATE_PACKAGES_WITHOUT_USER_ACTION),
            PermissionBean(Manifest.permission.USE_FINGERPRINT),
            PermissionBean(Manifest.permission.WRITE_EXTERNAL_STORAGE),
            PermissionBean(Manifest.permission.WRITE_SETTINGS),
            PermissionBean(Manifest.permission.WRITE_SYNC_SETTINGS),
        )

        @SuppressLint("InlinedApi")
        val sensitivePermissions = arrayListOf(
            PermissionBean(Manifest.permission.ACCESS_BACKGROUND_LOCATION, isSensitive = true),
            PermissionBean(Manifest.permission.ACCESS_COARSE_LOCATION, isSensitive = true),
            PermissionBean(Manifest.permission.ACCESS_FINE_LOCATION, isSensitive = true),
            PermissionBean(Manifest.permission.ACCESS_MEDIA_LOCATION, isSensitive = true),
            PermissionBean(Manifest.permission.CAMERA, isSensitive = true),
            PermissionBean(Manifest.permission.RECORD_AUDIO, isSensitive = true),
            PermissionBean(Manifest.permission.RECEIVE_BOOT_COMPLETED, isSensitive = true),
            PermissionBean(Manifest.permission.READ_CONTACTS, isSensitive = true),
            PermissionBean(Manifest.permission.WRITE_CONTACTS, isSensitive = true),
            PermissionBean(Manifest.permission.GET_ACCOUNTS, isSensitive = true),
            PermissionBean(Manifest.permission.READ_PHONE_STATE, isSensitive = true),
            PermissionBean(Manifest.permission.READ_PHONE_NUMBERS, isSensitive = true),
            PermissionBean(Manifest.permission.CALL_PHONE, isSensitive = true),
            PermissionBean(Manifest.permission.READ_CALL_LOG, isSensitive = true),
            PermissionBean(Manifest.permission.WRITE_CALL_LOG, isSensitive = true),
            PermissionBean(Manifest.permission.ANSWER_PHONE_CALLS, isSensitive = true),
            PermissionBean(Manifest.permission.BODY_SENSORS, isSensitive = true),
            PermissionBean(Manifest.permission.ACTIVITY_RECOGNITION, isSensitive = true),
            PermissionBean(Manifest.permission.SEND_SMS, isSensitive = true),
            PermissionBean(Manifest.permission.RECEIVE_SMS, isSensitive = true),
            PermissionBean(Manifest.permission.READ_SMS, isSensitive = true),
            PermissionBean(Manifest.permission.READ_CALENDAR, isSensitive = true),
            PermissionBean(Manifest.permission.WRITE_CALENDAR, isSensitive = true),
            PermissionBean(Manifest.permission.QUERY_ALL_PACKAGES, isSensitive = true),
        )

    }
}