package com.gh.gamecenter.common.utils

import android.content.Context
import android.content.res.Configuration
import androidx.appcompat.app.AppCompatDelegate
import com.gh.gamecenter.common.BuildConfig
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.core.utils.SPUtils

object DarkModeUtils {
    /**
     * 当前应用的深色模式是否生效中
     */
    fun isDarkModeOn(context: Context): Boolean {
        // 仅配置开启的包才提供深色模式功能
        return if (BuildConfig.IS_DARK_MODE_ON) {
            val uiMode = context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
            uiMode == Configuration.UI_MODE_NIGHT_YES
        } else {
            false
        }
    }

    /**
     * 获取是否跟随系统，默认false
     */
    fun isFollowSystemDarkModeFromSp() = SPUtils.getBoolean(Constants.SP_FOLLOW_SYSTEM_DARK_MODE_ENABLED, false)

    fun updateFollowSystemDarkModeToSp(follow: Boolean) =
        SPUtils.setBoolean(Constants.SP_FOLLOW_SYSTEM_DARK_MODE_ENABLED, follow)

    /**
     * 获取是否设置深色模式，默认false
     */
    fun isAppDarkModeEnabledFromSp() = SPUtils.getBoolean(Constants.SP_DARK_MODE_ENABLED, false)

    fun updateAppDarkModeStatusToSp(darkModeEnabled: Boolean) =
        SPUtils.setBoolean(Constants.SP_DARK_MODE_ENABLED, darkModeEnabled)

    fun initDarkMode() {
        initDarkMode(isFollowSystemDarkModeFromSp(), isAppDarkModeEnabledFromSp())
    }

    /**
     * 初始化App深色模式
     *
     * @param followSystem 是否是跟随系统
     * @param darkModeIsOn  是否是深色模式
     */
    fun initDarkMode(followSystem: Boolean, darkModeIsOn: Boolean) {
        // 仅配置开启的包才提供深色模式功能
        if (BuildConfig.IS_DARK_MODE_ON) {
            if (followSystem) {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
            } else {
                if (darkModeIsOn) {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                } else {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
                }
            }
        }
    }
}