import { removeIn, setIn } from "immutable";
import * as ReadOnlyDocuments from "./read-only-documents";
import { ActionTypes, isKnownAction } from "../actions";
import { isElementReference } from "./read-only-documents";
function apply(data, operation) {
  let applied = data;
  operation.forEach((component) => {
    if (component.ld != null)
      applied = removeIn(applied, component.p);
    if (component.od != null)
      applied = removeIn(applied, component.p);
    if (component.li != null)
      applied = setIn(applied, component.p, component.li);
    if (component.oi != null)
      applied = setIn(applied, component.p, component.oi);
  });
  return applied;
}
function getInitialState({
  documents = []
} = {}) {
  return ReadOnlyDocuments.getInitialState({ documents });
}
function getReadOnlyDocumentsStateSlice(state) {
  return state;
}
function getDocument(state, documentKey) {
  return ReadOnlyDocuments.getDocument(getReadOnlyDocumentsStateSlice(state), documentKey);
}
function getDocuments(state) {
  return ReadOnlyDocuments.getDocuments(getReadOnlyDocumentsStateSlice(state));
}
function reducer(state = getInitialState(), action) {
  const nextState = ReadOnlyDocuments.reducer(state, action);
  if (!isKnownAction(action))
    return state;
  switch (action.type) {
    case ActionTypes.CHANGE_DOCUMENT: {
      const document = getDocument(nextState, action.payload.documentKey);
      if (document == null)
        return nextState;
      const currentRootElement = ReadOnlyDocuments.getRootElement(document);
      const nextRootElement = apply(currentRootElement, action.payload.operation);
      return currentRootElement === nextRootElement ? nextState : new Map(nextState).set(action.payload.documentKey, {
        ...document,
        rootElement: nextRootElement
      });
    }
    default:
      return nextState;
  }
}
export {
  getDocument,
  getDocuments,
  getInitialState,
  isElementReference,
  reducer
};
//# sourceMappingURL=read-write-documents.js.map