import type {
  CircleType,
  CourseCompletionStatus,
  LearningSequence,
  LearningUnit,
} from "@/types";

export function circleFlatChildren(circle: CircleType) {
  return [
    ...circleFlatLearningContents(circle),
    ...circleFlatLearningUnits(circle).flatMap((lu) => {
      return lu.performance_criteria;
    }),
  ];
}

export function circleFlatLearningContents(circle: CircleType) {
  return circleFlatLearningUnits(circle).flatMap((lu) => {
    return lu.learning_contents;
  });
}

export function circleFlatLearningUnits(circle: CircleType) {
  return circle.learning_sequences.flatMap((ls) => {
    return ls.learning_units;
  });
}

export function learningSequenceFlatChildren(ls: LearningSequence) {
  return [
    ...ls.learning_units.flatMap((lu) => {
      return lu.learning_contents;
    }),
    ...ls.learning_units.flatMap((lu) => {
      return lu.performance_criteria;
    }),
  ];
}

export function someFinishedInLearningSequence(ls: LearningSequence) {
  return learningSequenceFlatChildren(ls).some((lc) => {
    return lc.completion_status === "SUCCESS";
  });
}

export function allFinishedInLearningSequence(ls: LearningSequence) {
  return learningSequenceFlatChildren(ls).every((lc) => {
    return lc.completion_status === "SUCCESS";
  });
}

export function calcSelfEvaluationStatus(
  learningUnit: LearningUnit
): CourseCompletionStatus {
  if (learningUnit.performance_criteria.length > 0) {
    if (
      learningUnit.performance_criteria.every((q) => q.completion_status === "SUCCESS")
    ) {
      return "SUCCESS";
    }
    if (
      learningUnit.performance_criteria.every(
        (q) => q.completion_status === "FAIL" || q.completion_status === "SUCCESS"
      )
    ) {
      return "FAIL";
    }
  }
  return "UNKNOWN";
}
