import { useContext } from "react";
import JobContext, { jobStatus } from "@qltr/jobs";

import CheckIcon from "@mui/icons-material/Check";
import ClearIcon from "@mui/icons-material/Clear";
import ViewColumnIcon from "@mui/icons-material/ViewColumn";
import PendingIcon from "@mui/icons-material/Pending";
import VisibilityIcon from "@mui/icons-material/Visibility";
import DoNotDisturbIcon from "@mui/icons-material/DoNotDisturb";
import ReplayIcon from "@mui/icons-material/Replay";

function statusIcon(status) {
  switch (status) {
    case jobStatus.OK:
      return <CheckIcon color="success" />;
    case jobStatus.ERROR:
      return <ClearIcon color="error" />;
    case jobStatus.PENDING:
      return <PendingIcon color="info" />;
    case jobStatus.ACTIVE:
      return <VisibilityIcon color="primary" />;
    case jobStatus.CANCELED:
      return <DoNotDisturbIcon color="warning" />;
    case jobStatus.QUEUED:
      return <ViewColumnIcon color="secondary" />;
    default:
      return <ReplayIcon />;
  }
}
export const pipelineJobs = (pipeline, jobs) =>
  jobs.filter((j) => j.isPipeline && j.pipelineId === pipeline.id);

export const useJobIconState = (job) => statusIcon(job.status);

export const usePipelineIconState = (pipeline) => {
  const { state: jobState } = useContext(JobContext);
  const jobStatuses = pipelineJobs(pipeline, jobState.jobs).map(
    (j) => j.status
  );
  if (jobStatuses.includes(jobStatus.ERROR)) return statusIcon(jobStatus.ERROR);

  if (jobStatuses.includes(jobStatus.ACTIVE))
    return statusIcon(jobStatus.ACTIVE);
  if (jobStatuses.includes(jobStatus.PENDING))
    return statusIcon(jobStatus.PENDING);
  if (pipeline.isCanceled) return statusIcon(jobStatus.CANCELED);
  return statusIcon(jobStatus.QUEUED);
};

export const selectedPipelineBranches = (pipeline) =>
  pipeline.branches.map((b) =>
    b.filter((t) => pipeline.selectedBranches.includes(t))
  );

export const findPipelineJobByTestName = (pipeline, jobs, testName) =>
  pipelineJobs(pipeline, jobs).find((j) => j.branchId === testName);
