// Import types
import OccurrenceBasicInfo from '../types/OccurrenceBasicInfo';

// Import helpers
import parseMMDDYY from './parseMMDDYY';

/**
 * Parse an occurrence ID string into an Occurrence object.
 * Expects input to be like an OccurrenceId (see types).
 * Throws a TypeError if input is in wrong format.
 * @author Benedikt Arnarsson
 * @param occStr - the occurrence ID.
 * @returns an object containing course, event, series, and data info.
 */
const parseOccurrenceId = (occStr: string): OccurrenceBasicInfo => {
  const occData = occStr.split('-');

  if (occData.length !== 3) {
    // FIXME: make ErrorCode for this
    throw new TypeError('Occurrence ID in the wrong format (invalid number of IDs).');
  }

  // FIXME: do we want this check? is the 'G' required?
  const markers = ['', 'G', 'O'];
  occData.forEach((id, index) => {
    const marker = markers[index];
    if (!id.startsWith(marker)) {
      // FIXME: make ErrorCode for this
      throw new TypeError('Occurrence ID in the wrong format (invalid ID markers).');
    }
  });

  const courseId = Number.parseInt(occData[0], 10);
  const ihid = occData[1];
  const mmddyy = parseMMDDYY(occData[2].slice(1));

  return {
    courseId,
    ihid,
    ...mmddyy,
  };
};

export default parseOccurrenceId;
