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

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

const localStorage = { setItem: () => {}, getItem: () => {} };

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

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

const initialState = {
  pages: ["failing", "alerting", "jobs", "catalog", "settings", "about"],
  intervals: [],
  regions: [],
  catalogSearch: "",
  ...settings,
};

const settingsUpdater = (oldState, storeUpdate) => {
  const settingsToUpdate = {};
  for (var k of settingsKeys) {
    settingsToUpdate[k] = oldState[k];
    if (storeUpdate[k] === undefined) continue;
    settingsToUpdate[k] = storeUpdate[k];
  }

  localStorage.setItem("settings", JSON.stringify(settingsToUpdate));
};

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

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

  function silenceRequest(silenceInfo) {
    const req = {
      name: silenceInfo.name ?? "*",
      class: silenceInfo.class ?? "*",
      method: silenceInfo.method ?? "*",
      silencedUntil: silenceInfo.silencedUntil,
    };
    console.log("Would upsert silence", req);
  }

  function removeFailure(failure) {
    const req = {
      name: failure.name,
      class: failure.class,
    };
    console.log("Would remove failure", req);
  }

  const context = {
    state,
    dispatch,
    silenceRequest,
    removeFailure,
    updateStore: (store) => dispatch({ type: ACTIONS.UPDATE, store }),
  };
  const contextValue = useMemo(() => context, [state, dispatch]);

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

export default StoreContext;
