import type { components } from "../api/schema";

import { labelText } from "./labels";

type LabelView = components["schemas"]["LabelView"];

const collators = new Map<string, Intl.Collator>();

function collatorFor(lang: string): Intl.Collator {
  let c = collators.get(lang);

  if (!c) {
    c = new Intl.Collator(lang, { sensitivity: "base", numeric: true });
    collators.set(lang, c);
  }

  return c;
}

export function compareStrings(lang: string, a: string, b: string): number {
  return collatorFor(lang).compare(a, b);
}

export function byLabel(lang: string) {
  return (a: { labels: LabelView[] }, b: { labels: LabelView[] }) =>
    compareStrings(lang, labelText(a.labels, lang), labelText(b.labels, lang));
}

export function byKey(lang: string) {
  return (a: { key: string }, b: { key: string }) => compareStrings(lang, a.key, b.key);
}
