import * as A from "fp-ts-esm/Array";
import { constFalse, constTrue, flow, identity, pipe } from "fp-ts-esm/function";
import * as M from "fp-ts-esm/Monoid";
import * as O from "fp-ts-esm/Option";
import * as R from "fp-ts-esm/Record";
import lodash from "lodash";
import { fromRichTextHtml } from "../../converters/html/index.js";
import { firstRight } from "../../fp-utils.js";
import { modify } from "../../RicosContentAPI/modify.js";
import { isNonTextualNode, isTextualNode } from "../types.js";
const toTranslatableById = (node) => ({
  [node.id]: [node]
});
const TranslatableMapM = R.getMonoid(A.getSemigroup());
const fromHtml = (node) => (translatable) => ({
  ...node,
  nodes: fromRichTextHtml(translatable[0].text)?.nodes?.[0]?.nodes ?? []
});
const translateTextualNode = (translations) => (node) => pipe(
  translations,
  R.lookup(node.id),
  O.map(fromHtml(node)),
  O.fold(() => node, identity)
);
const setWithTranslations = (node) => (translatables) => {
  const newNode = lodash.cloneDeep(node);
  translatables.forEach(
    ({ path, text }) => !!lodash.get(newNode, path, false) && lodash.set(newNode, path, text)
  );
  return newNode;
};
const translateNonTextualNode = (translations) => (node) => pipe(
  translations,
  // @ts-ignore $TsFixMe
  R.lookup(node.id),
  O.map(setWithTranslations(node)),
  O.fold(() => node, identity)
);
const toTranslatableMap = flow(
  A.map(toTranslatableById),
  M.concatAll(TranslatableMapM)
);
const translatableNode = (translations) => (node) => pipe(translations, R.lookup(node.id), O.fold(constFalse, constTrue));
const translatedNode = (translations) => (node) => firstRight(node, node, [
  [isTextualNode, translateTextualNode(translations)],
  [isNonTextualNode, translateNonTextualNode(translations)]
]);
const translateContent = (content, translatables) => {
  const translationMap = toTranslatableMap(translatables);
  return modify(content).filter(translatableNode(translationMap)).set(translatedNode(translationMap));
};
export {
  translateContent
};
//# sourceMappingURL=translate-content.js.map
