package com.yidian.bcommon.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings


/**
 * 系统设置工具类
 */
object SystemSettingUtils {

  /**
   * 打开通知设置
   */
  fun openNotifySetting(activity: Activity) {
    try {
      //8.0及以后版本使用这两个extra.  >=API 26
      if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        val intent = Intent()
        intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
        intent.putExtra(Settings.EXTRA_APP_PACKAGE, activity.packageName)
        intent.putExtra(Settings.EXTRA_CHANNEL_ID, activity.applicationInfo.uid)
        activity.startActivity(intent)
      } else {
        //其他低版本或者异常情况，走该节点。进入APP设置界面
        toApplicationInfo(activity)
      }
    } catch (e: Exception) {
      e.printStackTrace()
      //其他低版本或者异常情况，走该节点。进入APP设置界面
      toSystemConfig(activity)
    }
  }

  /**
   * 应用信息界面
   *
   * @param activity
   */
  private fun toApplicationInfo(activity: Activity) {
    val localIntent = Intent()
    localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    localIntent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
    localIntent.data = Uri.fromParts("package", activity.packageName, null)
    activity.startActivity(localIntent)
  }

  /**
   * 系统设置界面
   *
   * @param activity
   */
  fun toSystemConfig(activity: Activity) {
    try {
      val intent = Intent(Settings.ACTION_SETTINGS)
      activity.startActivity(intent)
    } catch (e: Exception) {
      e.printStackTrace()
    }
  }

  /**
   * 打开应用设置详情页,进行权限管理
   */
  fun openAppSettingDetail(context: Context) {
    val intent = Intent()
    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
    intent.addCategory(Intent.CATEGORY_DEFAULT)
    intent.data = Uri.parse("package:" + context.packageName)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
    intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
    context.startActivity(intent)
  }
}
