package com.convenient.android.common.extension

import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.media.AudioManager
import android.os.Build
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.core.view.WindowInsetsCompat

/**
 * @classname:SystemExtensions
 * @author: LiuXiaoLong
 * @date: 2022/7/27
 * description: 系统相关的一些扩展
 */


/**
 * 判断是否为暗黑模式
 */
fun Context.isNightMode(): Boolean = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES



/****** 设定是否静音 ******/
fun Context.isSysVolumeMute(isMute: Boolean = false) {
    (getSystemService(Context.AUDIO_SERVICE) as AudioManager?)?.let {
        when {
            isMute -> {//静音
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    it.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, AudioManager.FLAG_VIBRATE)
                } else {
                    it.setStreamMute(AudioManager.STREAM_MUSIC, true)
                }
            }
            else -> {//关闭静音
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    it.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, AudioManager.FLAG_VIBRATE)
                } else {
                    it.setStreamMute(AudioManager.STREAM_MUSIC, false)
                }
            }
        }
    }
}


/**
 * 展示KeyBoard
 */
fun View.showKeyboard() {
    postDelayed({
        isFocusable = true
        isFocusableInTouchMode = true
        requestFocus()
        val imm = context.applicationContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(this, InputMethodManager.SHOW_FORCED)
    }, 300)
}

/**
 * 隐藏KeyBoard
 */
fun View.hideKeyboard(): Boolean {
    context.runCatching {
        val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        return inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
    }
    return false
}

/**
 * 隐藏键盘
 */
fun Activity.hideSoftKeyboard() {
    getWindowInsetsController().hide(WindowInsetsCompat.Type.ime())
}

/**
 * 显示键盘
 */
fun Activity.showSoftKeyboard() {
    getWindowInsetsController().show(WindowInsetsCompat.Type.ime())
}



