import { getPropControllerDescriptors } from "../react-page";
import * as Documents from "../modules/read-only-documents";
import {
  mergeGridPropControllerTranslatedData,
  Types as PropControllerTypes
} from "@makeswift/prop-controllers";
import { ReactMergeTranslationsVisitor } from "../../controls/visitors/merge-translations-visitor";
import { isLegacyDescriptor } from "../../prop-controllers/descriptors";
function mergeElementTreeTranslatedData(state, elementTree, translatedData) {
  function merge(state2, translatedData2) {
    return function(node) {
      if (Documents.isElementReference(node))
        return node;
      const elementDescriptors = getPropControllerDescriptors(state2);
      const descriptors = elementDescriptors.get(node.type);
      if (descriptors == null) {
        throw new Error(`Can't merge element of type "${node.type}" because it has no descriptors`);
      }
      const context = {
        translatedData: translatedData2,
        mergeTranslatedData: merge(state2, translatedData2)
      };
      const props = {};
      for (const propName of Object.keys(descriptors)) {
        const descriptor = descriptors[propName];
        props[propName] = mergeTranslatedData(
          descriptor,
          node.props[propName],
          translatedData2[`${node.key}:${propName}`],
          context
        );
      }
      return { ...node, props };
    };
  }
  return merge(state, translatedData)(elementTree);
}
function mergeTranslatedData(definition, data, translatedData, context) {
  if (data == null)
    return data;
  if (!isLegacyDescriptor(definition)) {
    const mergeTranslationsVisitor = new ReactMergeTranslationsVisitor(context);
    return definition.accept(mergeTranslationsVisitor, data, translatedData);
  }
  switch (definition.type) {
    case PropControllerTypes.TextInput:
    case PropControllerTypes.TextArea:
      if (translatedData == null)
        return data;
      return translatedData;
    case PropControllerTypes.Grid:
      return mergeGridPropControllerTranslatedData(data, context);
    default:
      return data;
  }
}
export {
  mergeElementTreeTranslatedData,
  mergeTranslatedData
};
//# sourceMappingURL=merge.js.map