import { useContext } from "react";
import { useNavigate } from "react-router-dom";
import JobContext from "@qltr/jobctx";
import { jobStatus } from "./job-config.js";
// Icons
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 TimerIcon from "@mui/icons-material/Timer";
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" />;
    case jobStatus.TIMER:
      return <TimerIcon color="primary" />;
    default:
      return <ReplayIcon />;
  }
}

export function useJobExtras() {
  const { state, jobUpdate, jobCreate, jobDelete } = useContext(JobContext);
  const navigate = useNavigate();

  function pipelineJobs(pl) {
    return state.jobs.filter((j) => j.isPipeline && j.pipelineId === pl.id);
  }

  const jobIcon = ({ status }) => statusIcon(status);

  function pipelineIcon(pl) {
    const jobStatuses = pipelineJobs(pl).map(({ status }) => status);
    if (pl.pendingTriggers.length > 0) return statusIcon(jobStatus.TIMER);
    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 (pl.isCanceled) return statusIcon(jobStatus.CANCELED);
    if (jobStatuses.includes(jobStatus.OK)) return statusIcon(jobStatus.OK);
    return statusIcon(jobStatus.QUEUED);
  }

  function selectedPipelineBranches(pl) {
    return pl.branches.map((b) =>
      b.filter((t) => pl.selectedBranches.find((b) => b.name == t.name))
    );
  }

  function findPipelineJobByTestName(pl, testName) {
    return pipelineJobs(pl).find((j) => j.branchId === testName);
  }

  // Nav
  const toJob = (jobId) => navigate(`/qualiteer/jobs#job-${jobId}`);
  const toPipeline = (plId) => navigate(`/qualiteer/jobs#pipeline-${plId}`);
  const toJobs = () => navigate(`/qualiteer/jobs`);

  return {
    pipelineJobs,
    jobIcon,
    pipelineIcon,
    selectedPipelineBranches,
    findPipelineJobByTestName,
    toJob,
    toPipeline,
    toJobs,
  };
}
