import React, { useReducer, createContext, useMemo } from "react";
const SettingsContext = createContext();

const ACTIONS = {
  UPDATE: "u",
};

const localSettings = localStorage.getItem("settings");
const defaultSettings = {
  simplifiedControls: false,
  logAppDetails: true,
  defaultPage: "home",
};

const settings = localSettings ? JSON.parse(localSettings) : defaultSettings;
const settingsKeys = Object.keys(defaultSettings);

const initialState = {
  pages: ["home"],
  ...settings,
};

const settingsUpdater = (oldState, settingsUpdate) => {
  const settingsToUpdate = {};
  for (var k of settingsKeys) {
    settingsToUpdate[k] = oldState[k];
    if (settingsUpdate[k] === undefined) continue;
    settingsToUpdate[k] = settingsUpdate[k];
  }
  localStorage.setItem("settings", JSON.stringify(settingsToUpdate));
};

const reducer = (state, action) => {
  const { settings } = action;
  // Actions
  switch (action.type) {
    case ACTIONS.UPDATE:
      settingsUpdater(state, settings);
      return { ...state, ...settings };
    default:
      return state;
  }
};

export const SettingsProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  const context = {
    state,
    dispatch,
    updateSettings: (settings) => dispatch({ type: ACTIONS.UPDATE, settings }),
  };
  const contextValue = useMemo(() => context, [state, dispatch]);

  return (
    <SettingsContext.Provider value={contextValue}>
      {children}
    </SettingsContext.Provider>
  );
};

export default SettingsContext;
