import {StorageKeys} from "../../globalConstants";
import {COLOR_PRIMARY} from "../../app/pages/LoginPage/constants";

/**
 * 判断窗口是否为黑色主题
 */
/* istanbul ignore next line */
export const isSystemDark = window?.matchMedia
  ? window.matchMedia('(prefers-color-scheme: dark)')?.matches
  : undefined;

/**
 * 将主题变量存入浏览器缓存
 * @param theme
 */
export function saveTheme(theme) {
  window.localStorage && localStorage.setItem(StorageKeys.Theme, theme);
}


/**
 * 获取本地缓存中的主题变量
 */
/* istanbul ignore next line */
export function getThemeFromStorage() {
  let theme = 'LIGHT';
  try {
    const storedTheme = window.localStorage && localStorage.getItem(StorageKeys.Theme);
    if (storedTheme) {
      theme = storedTheme;
    }
  } catch (error) {
    throw error;
  }
  return theme;
}

/**
 * 将主题配置存入浏览器缓存
 * @param config
 */
export function saveThemeConfig(config) {
  if (typeof config === 'object') {
    const now = getThemeConfigFromStorage();
    // 局部覆盖
    const newConfig = {
      ...now,
      ...config
    };
    window.localStorage && localStorage.setItem(StorageKeys.ThemeConfig, JSON.stringify(newConfig));
  }

}

/**
 * 获取本地缓存中的主题配置
 */
/* istanbul ignore next line */
export function getThemeConfigFromStorage() {
  let config = {
    color:COLOR_PRIMARY.LEVEL1,
    radius:6,
    compact:false,
    lang:'zh',
  };
  try {
    const storedConfig = window.localStorage && localStorage.getItem(StorageKeys.ThemeConfig);
    if (storedConfig) {
      config = JSON.parse(storedConfig);
    }
  } catch (error) {
    throw error;
  }
  return config;
}
