import { defaultLocale, getLocale, locales } from 'astro-i18n-aut';
import { ui, defaultLang, showDefaultLang } from './ui';

export function useTranslatedPath(url: URL) {
  const locale = getLocale(url);
  return function translatePath(path: string, l: string = locale) {
    return !showDefaultLang && l === defaultLang ? path : `/${l}${path}`.replace(/\/$/g, '');
  }
}

export function useTranslations(url: URL) {
  const lang = getLocale(url);
  return function t(key: keyof typeof ui[typeof defaultLang]) {
    return ui[lang as keyof typeof ui][key] || ui[defaultLang][key];
  }
}

export function parseSlug(id: string) {
  const splitPath = id.split('/');
  const split = splitPath.pop()?.split('.').map(s => s.replace(/^index/, ""));
  for (const s of split || []) {
    if (locales[s]) {
      return [splitPath[0] ?? id, s]
    }
  }
  return [splitPath[0] ?? id, defaultLocale]
}

export function filterCollection<T extends { id: string, data: { draft?: boolean, date?: Date } }>(collection: T[], locale: string): T[] {
  return collection.filter(post => {
    const [_, lang] = parseSlug(post?.id);
    if (post?.data?.draft) return false;
    return lang === locale;
  }).sort((a, b) => {
    if (!a?.data?.date || !b?.data?.date) return 0;
    return (a?.data?.date > b?.data?.date) ? -1 : 1;
  });
}
