// SPDX-FileCopyrightText: 2021 Johannes Loher
//
// SPDX-License-Identifier: MIT

export function registerHandlebarsHelpers(): void {
  Handlebars.registerHelper(helpers);
}

const helpers = {
  htmlToPlainText: (input: string | null | undefined): string | null | undefined => {
    if (!input) return;
    return $(input).text();
  },

  isEmpty: (input: Array<unknown> | null | undefined): boolean => (input?.length ?? 0) === 0,

  toRomanNumerals,
};

function toRomanNumerals(number: number): string {
  return [...generateRomanNumerals(number, 0)].join("");
}

function* generateRomanNumerals(number: number, numeralIndex: number): Generator<string> {
  if (number === 0) return;
  const currentNumeral = numerals[numeralIndex];
  if (currentNumeral === undefined) return;

  const quotient = number / currentNumeral;
  const remainder = number % currentNumeral;
  const numberAsNumerals = numeralLookup[currentNumeral].repeat(quotient);

  yield numberAsNumerals;
  yield* generateRomanNumerals(remainder, numeralIndex + 1);
}

const numeralLookup = {
  1: "I",
  2: "II",
  3: "III",
  4: "IV",
  5: "V",
  6: "VI",
  7: "VII",
  8: "VIII",
  9: "IX",
  10: "X",
  20: "XX",
  30: "XXX",
  40: "XL",
  50: "L",
  60: "LX",
  70: "LXX",
  80: "LXXX",
  90: "XC",
  100: "C",
  200: "CC",
  300: "CCC",
  400: "CD",
  500: "D",
  600: "DC",
  700: "DCC",
  800: "DCCC",
  900: "CM",
  1000: "M",
};

const numerals = [
  1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
] as const;
