package com.wdkl.app.ncs.callingbed.helper

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log

class ScreenManagerUtil {


    /**
     * @return 0--255
     */
    fun getScreenBrightness(context: Context): Int {
        var screenBrightness = 150

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(context)) {
                val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
                intent.data = Uri.parse("package:" + context.packageName)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                context.startActivity(intent)
            } else {
                //有了权限，具体的动作
                try {
                    screenBrightness = Settings.System.getInt(context.contentResolver,
                            Settings.System.SCREEN_BRIGHTNESS)
                } catch (e: Settings.SettingNotFoundException) {
                    e.printStackTrace()
                }

            }
        } else {
            try {
                screenBrightness = Settings.System.getInt(context.contentResolver,
                        Settings.System.SCREEN_BRIGHTNESS)
            } catch (e: Settings.SettingNotFoundException) {
                e.printStackTrace()
            }

        }

        return screenBrightness
    }


    /**
     * 保存当前的屏幕亮度值，并使之生效
     *
     * @param paramInt 0-255
     */
    fun setScreenBrightness(context: Context, paramInt: Int) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(context)) {
                val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
                intent.data = Uri.parse("package:" + context.packageName)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                context.startActivity(intent)
            } else {
                //有了权限，具体的动作
                Settings.System.putInt(context.contentResolver,
                        Settings.System.SCREEN_BRIGHTNESS, paramInt)
                val uri = Settings.System
                        .getUriFor("screen_brightness")
                Log.w("当前亮度", "当前亮度======" + getScreenBrightness(context))
                context.contentResolver.notifyChange(uri, null)
            }
        } else {
            Settings.System.putInt(context.contentResolver,
                    Settings.System.SCREEN_BRIGHTNESS, paramInt)
            val uri = Settings.System
                    .getUriFor("screen_brightness")
            Log.w("当前亮度", "当前亮度======" + getScreenBrightness(context))
            context.contentResolver.notifyChange(uri, null)
        }

    }
}