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

export const jobStatus = {
  OK: "o",
  QUEUED: "q",
  PENDING: "p",
  CANCELED: "c",
  ACTIVE: "a",
  ERROR: "e",
};

const ACTIONS = {
  CREATE: "c",
  UPDATE: "u",
  DELETE: "d",
};
/**/
const jobMock = Object.values(jobStatus).map((v, i) => ({
  name: `Job${i + 1}`,
  test: `someTestName${i + 1}`,
  status: v,
  exitcode: 0,
}));

const initialState = {
  jobs: jobMock,
};
/*
{
 name: "Job1",
 test: "someTestName",
 status: JOB_STATUS.SUCCESS,
 exitcode: 0
}

OR
{
  compound: true,
  name: "Compound Job",
  pipeline: [{}]
}

*/

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 jobUpdate = (job, jobId) =>
    dispatch({ type: ACTIONS.UPDATE, jobId, job });
  const jobCreate = (job) =>
    dispatch({ type: ACTIONS.CREATE, job: { ...job, log: [] } });
  const jobDelete = (jobId) => dispatch({ type: ACTIONS.DELETE, jobId });

  function retryAll(failing) {
    // Query Full Locator
    console.log("Would retry all failing tests!");
  }

  function activeJobStates() {
    const jobs = { state };
    console.log("Would return all active job states");
  }

  function mockRun() {
    dispatch({
      job: {
        name: "Job1",
        test: "someTestName",
        log: [],
        status: jobStatus.OK,
        exitcode: 0,
      },
      action: ACTIONS.CREATE,
    });
  }

  function jobBuilder(tests) {
    if (!Array.isArray(tests)) throw Error("Error from within JobContext.jsx");
    console.log("Would run tests", tests);
  }

  function retrySingle(test) {
    console.log("Would retry test", test);
  }

  const context = {
    state,
    dispatch,
    jobUpdate,
    jobCreate,
    jobDelete,
    retryAll,
    retrySingle,
    jobBuilder,
    activeJobStates,
  };
  const contextValue = useMemo(() => context, [state, dispatch]);

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

export default JobContext;
