import {createSlice} from "@reduxjs/toolkit";

import {useInjectReducer} from "../../../utils/@reduxjs/injectReducer";

import {getThemeFromStorage, saveTheme, saveThemeConfig} from "../utils";
import {COLOR_PRIMARY} from "../../../app/pages/LoginPage/constants";

export const initialState  ={
  openDesigner:false,
  theme:getThemeFromStorage(),
  color:COLOR_PRIMARY.LEVEL1,
  radius:6,
  compact:false,
  lang:'zh',
}

/**
 * 主题Redux切片管理
 * use : dispatch(themeSlice.actions.changeTheme('dark'));
 */
const themeSlice = createSlice({
  name:'theme',
  initialState,
  reducers:{
    changeTheme(state, action) {
      const {theme,color,radius} = action.payload;
      state.theme = theme;
      state.color = color;
      state.radius = radius;
      saveTheme(theme);
      saveThemeConfig(action.payload)
    },
    changeColor(state, action) {
      const color = COLOR_PRIMARY[action.payload] || action.payload;
      state.color=color;
      saveThemeConfig({color});
    },
    changeCompact(state, action) {
      const compact = action.payload;
      state.compact=action.payload;
      saveThemeConfig({compact});
    },
    changeRadius(state, action) {
      const radius = action.payload;
      state.radius=action.payload;
      saveThemeConfig({radius});
    },
    openThemeDesigner(state, action) {
      state.openDesigner = action.payload;
    },
  }
})

export default themeSlice;

export const { actions: themeActions, reducer } = themeSlice;

export const useThemeSlice = () => {
  useInjectReducer({ key: themeSlice.name, reducer: themeSlice.reducer });
  return { actions: themeSlice.actions };
};
