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

const ACTIONS = {
  CREATE: "c",
  UPDATE: "u",
  DELETE: "d",
};

const initialState = {
  jobs: [],
};

const reducer = (state, action) => {
  // Current Jobs
  const { jobs } = state;
  var jobIndex;
  // Actions
  switch (action.type) {
    case ACTIONS.CREATE:
      jobs.push(action.job);
      return { ...state, jobs };

    case ACTIONS.UPDATE:
      jobIndex = jobs.find((j) => j.id === (action.job.id ?? action.jobId));
      jobs[jobIndex] = action.job;
      return { ...state, jobs };

    case ACTIONS.DELETE:
      jobIndex = jobs.find((j) => j.id === action.jobId);
      jobs.splice(jobIndex, 1);
      return { ...state, jobs };

    default:
      return state;
  }
};

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

  const context = {
    state,
    dispatch,
    jobUpdate: (job, jobId) => dispatch({ type: ACTIONS.UPDATE, jobId, job }),
    jobCreate: (job) =>
      dispatch({ type: ACTIONS.CREATE, job: { ...job, log: [] } }),
    jobDelete: (jobId) => dispatch({ type: ACTIONS.DELETE, jobId }),
  };
  const contextValue = useMemo(() => context, [state, dispatch]);

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

export default JobContext;
