import {createSelector} from "@reduxjs/toolkit";
import {initialState} from "./index";

import {getThemeConfigFromStorage, getThemeFromStorage, isSystemDark} from "../utils";
import {themes} from "../themes";
import {theme as antdTheme} from "antd";
import {antdThemeConfig} from "../themes";
import {COLOR_PRIMARY} from "../../../app/pages/LoginPage/constants";
/**
 * 注入一个主题初始变量key
 * @param state
 */
const selectDomain = (state) =>state.theme || initialState;

/**
 * 主题设计器状态
 */
export const selectDesignerStatus = createSelector(
  [selectDomain],
  theme=> theme.openDesigner
)


/**
 * 返回自定义主题Token
 */
export const selectTheme = createSelector(
  [selectDomain],
  theme=> {
    if (theme.theme==='system'){
      return isSystemDark ? themes.DARK :themes.LIGHT;
    }
    return themes[theme.theme];
  }
)

/**
 * 返回全局主题变量theme
 */
export const selectThemeKey = createSelector(
  [selectDomain],
  theme=>theme.theme
)

/**
 * 返回全局主题变量theme
 */
export const selectColorPrimary = createSelector(
  [selectDomain],
  theme=>theme.color
)

/**
 * 返回全局主题变量theme
 */
export const selectCompact = createSelector(
  [selectDomain],
  theme=>theme.compact
)

/**
 * 返回全局主题变量theme
 */
export const selectRadius = createSelector(
  [selectDomain],
  theme=>theme.radius
)

/**
 * 返回自定义、Antd主题 合并Token
 */
export const selectMergeTheme = createSelector(
  [selectDomain],
  theme=> {
    const localTheme = getThemeFromStorage();
    const token = antdTheme.useToken();
    const mergerToken= {
      ...token.token,
      ...themes[localTheme]
    }
    if (localTheme.theme==='system'){
      return isSystemDark ? themes.DARK :themes.LIGHT;
    }
    return mergerToken;
  }
)

/**
 * 返回Antd主题配置
 */
export const selectAntdThemeConfig = createSelector(
  [selectDomain],
  theme=> {
    const localTheme = getThemeFromStorage();
    const config = getThemeConfigFromStorage();
    const algorithm = antdThemeConfig[localTheme] || antdThemeConfig.LIGHT;
    let algorithms = [algorithm];
    if (config.compact){
      algorithms.push(antdThemeConfig.COMPACT);
    }
    return {
      algorithm:algorithms,
      token: {
        // Seed Token，影响范围大
        colorPrimary: config.color||COLOR_PRIMARY[config.color],
        borderRadius: config.radius
      },
    }
  }
)
