package com.rdiot.yx485.util;

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.clj.fastble.BleManager
import com.lindroy.iosdialog.IAlertDialog
import com.rdiot.yx485.R
import com.tbruyelle.rxpermissions2.RxPermissions
import java.util.concurrent.atomic.AtomicBoolean


object PermissionUtils {

    private var dialog: IAlertDialog? = null
    private var isShowingDialog = AtomicBoolean(false)

    fun checkPermissionGranted(activity: AppCompatActivity, action: String): Boolean {
        val permissionList = mutableListOf<String>()
        if (action == "enterWifi") {
            permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION)
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION)
        } else if (action == "ble") {
            permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION)
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION)

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                permissionList.add(Manifest.permission.BLUETOOTH_SCAN)
                permissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE)
                permissionList.add(Manifest.permission.BLUETOOTH_CONNECT)
            }
        } else {
            if (action == "scan") {
                permissionList.add(Manifest.permission.CAMERA)
            } else {
                permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }

        var list = mutableListOf<String>()
        for (permission in permissionList) {
            if (ContextCompat.checkSelfPermission(
                    activity,
                    permission
                ) == PackageManager.PERMISSION_DENIED
            ) {
                list.add(permission)
            }
        }

        if (list.isEmpty()) {
            return !(action == "ble" && !checkBlueState(activity))
        }

        showNeedPermissionDialog(activity, list, action)
        return false
    }

    private fun checkBlueState(context: AppCompatActivity): Boolean {
        if (!BleManager.getInstance().isBlueEnable) {
            // 蓝牙未开启
            showOpenBlueToothDialog(context)
            return false
        } else {
            // 蓝牙已开启
            return true
        }
    }

    private fun showOpenBlueToothDialog(context: AppCompatActivity) {
        if (dialog?.isVisible != true) {
            dialog?.dismiss()
            dialog = IAlertDialog.build(context)
                .setTitle("温馨提示")
                .setCancelOutside(false)
                .setShowNegButton(false)
                .setAlpha(1.0F)
                .setMessage("添加设备需要使用蓝牙功能，请打开蓝牙后使用")
                .setPosButtonText(R.string.got_it)
                .setPosClickListener {
                    BleManager.getInstance().enableBluetooth()
                    dialog?.dismiss()
                }
            dialog?.isCancelable = false
            dialog?.show()
        }
    }

    fun showNeedPermissionDialog(context: AppCompatActivity, list: List<String>, action: String) {
        var desc = "应用需要您允许以下权限才能正常使用："
        desc += if (action == "enterWifi") {
            "定位权限，用于获取设备Wi-Fi信息"
        } else if (action == "scan") {
            "相机权限，用于扫描设备码"
        } else if (action == "ble") {
            "蓝牙权限、附近设备权限，使用蓝牙发现和连接设备"
        } else {
            "照片和存储权限，用于修改头像"
        }
        if (dialog?.isVisible != true) {
            dialog?.dismiss()
            dialog = IAlertDialog.build(context)
                .setTitle(R.string.hint)
                .setMessage(desc)
                .setNegButtonText(R.string.cancel)
                .setCancelOutside(false)
                .setNegClickListener {
                    isShowingDialog.set(false)
                }
                .setAlpha(1.0F)
                .setPosButtonText("知道了")
                .setPosClickListener {
                    requestPermission(context, list)
                    isShowingDialog.set(false)
                }
            dialog?.show()
        }
    }

    @SuppressLint("CheckResult")
    fun requestPermission(context: AppCompatActivity, permissionList: List<String>) {
        RxPermissions(context)
            .requestEach(*permissionList.toTypedArray())
            .subscribe { permission ->  // will emit 2 Permission objects
                Log.d("checkPermission", "checkPermission: $permission")
                if (permission.granted) {
                    // `permission.name` is granted !
                    Log.d("checkPermission", "授权成功: ")
                } else if (permission.shouldShowRequestPermissionRationale) {
                    /* Denied permission without ask never again */
                    Log.d("checkPermission", "拒绝授权: ")
                } else {
                    // Denied permission with ask never again
                    // Need to go to the settings
                    showPermissionDeniedDialog(context)
                }
            }
    }

    private fun showPermissionDeniedDialog(context: AppCompatActivity) {
        if (dialog?.isVisible != true) {
            dialog?.dismiss()
            dialog = IAlertDialog.build(context)
                .setTitle(R.string.hint)
                .setMessage("应用需要您授权全部权限才能正常使用，请到系统设置中授权")
                .setNegButtonText(R.string.cancel)
                .setCancelOutside(false)
                .setNegClickListener {
                    isShowingDialog.set(false)
                }
                .setAlpha(1.0F)
                .setPosButtonText(R.string.go_setting)
                .setPosClickListener {
                    goToAppSetting(true, context)
                    isShowingDialog.set(false)
                }
            dialog?.show()
        }
    }

    /**
     * 打开App设置页面
     * @param justGo 直接跳转
     * @return [Intent] 意图
     */
    fun goToAppSetting(justGo: Boolean, context: AppCompatActivity): Intent {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri = Uri.fromParts("package", context.packageName, null)
        intent.data = uri
        if (justGo) context.startActivity(intent)
        return intent
    }
}