//@ts-check

import { today } from "../utils/today.mjs";

/**
 * @typedef {Exclude<ReturnType<typeof parseFileListLine>, null>} ParsedLine
 */

/**
 * Parses a single line of a file list
 * @param {string} line
 * @param {number} index
 * @returns
 */
export const parseFileListLine = (line, index) => {
  const result = line.match(
    /(?<name>.+)\.(?<ext>\w{2,3})(?:\s+(?<date>[\d-]+)?(?<title>.+))?/
  );
  if (!result) {
    return null;
  }
  const {
    //@ts-ignore
    groups: { name, ext, date = today, title = name },
  } = result;
  const href = `/${name}.${ext}`;
  const date_unix = new Date(date).getTime();
  return { name, href, date, title, date_unix, index };
};

/**
 * parses a filelist string. That's a string that looks like
 * ```md
 * name dd-mm-yyyy link name
 * name dd-mm-yyyy
 * name linkname
 * name
 * ```
 * This is very specific to Tickle and unlikely to be very useful anywhere else.
 * @param {string} lines
 */
export const parseFileList = (lines) =>
  // @ts-ignore
  lines
    .trim()
    .split(`\n`)
    .reduce((/** @type {ParsedLine[]}*/ arr, line, index) => {
      const result = parseFileListLine(line.trim(), index);
      if (!result) {
        console.error(`could not parse line number ${index}`);
        return arr;
      }
      arr.push(result);
      return arr;
    }, []);

parseFileList.parseLine = parseFileListLine;

export default parseFileList;
