import LanguageDetect from 'languagedetect';
import {languages} from 'prismjs/components';

const RESOLVED_ALIASES = Object.fromEntries(
  Object
    .entries(languages)
    .reduce(
      (resolved, [languageId, languageDefinition]) => {
        if (Array.isArray(languageDefinition.alias)) {
          return [
            ...resolved,
            ...(languageDefinition.alias.map((a: string) => [a, { aliasOf: languageId, title: languageDefinition.title, extension: `.${a}`} ])),
            [languageId, { title: languageDefinition.title, extension: `.${languageId}`}],
          ];
        }

        if (typeof languageDefinition.alias === 'string') {
          return [
            ...resolved,
            [languageDefinition.alias, { aliasOf: languageId, title: languageDefinition.title, extension: `.${languageDefinition.alias}`}],
            [languageId, { title: languageDefinition.title, extension: `.${languageId}`}],
          ];
        }

        return [
          ...resolved,
          [languageId, { title: languageDefinition.title, extension: `.${languageId}`}],
        ];
      },
      [] as [string, { aliasOf?: string, title: string, extension: string }][]
    )
);

export const getTextMetadata = (contents: string, filename: string) => {
  const metadata = Object.entries(RESOLVED_ALIASES).reduce(
    (theMetadata, [key, value]) => {
      if (typeof theMetadata.scheme === 'undefined' && filename.endsWith(value.extension)) {
        if (value.aliasOf) {
          return {
            ...theMetadata,
            scheme: value.aliasOf,
            schemeTitle: value.title,
          }
        }

        return {
          ...theMetadata,
          scheme: key,
          schemeTitle: value.title,
        };
      }

      return theMetadata;
    },
    {} as Record<string, number | string>
  );

  if (typeof metadata.scheme !== 'string') {
    const naturalLanguageDetector = new LanguageDetect();
    const probableLanguages = naturalLanguageDetector.detect(contents);
    const [languageName, probability] = probableLanguages[0];
    metadata.language = languageName;
    metadata.languageProbability = probability;
  }

  return metadata;
}
