import type { Controller } from "../index";
import { AnyOperation } from "../../persist";
import { Model } from "../../model";
import { Hooks, Setter } from "./type";
import { createSetterBook } from "./book";
import { Selection } from "../../editor";

export * from "./type";

export const createSetter = (controller: Controller, model: Model, hooks: Hooks): Setter => {
  let isNextSilent = false;
  let isNextPreteat = false;

  function apply(change: AnyOperation[], nextSelection?: Selection, extPayload?: any) {
    hooks.beforeApply(isNextSilent, extPayload);
    const inverse = model.applyOps(change);
    hooks.afterApply(change, inverse, nextSelection, isNextSilent, isNextPreteat);
    isNextSilent = false;
    isNextPreteat = false;
  }

  function nextApplyPreteat() {
    isNextPreteat = true;
  }

  function nextApplySilent() {
    isNextSilent = true;
  }

  return {
    apply,
    nextApplyPreteat,
    nextApplySilent,
    book: createSetterBook(controller, apply),
  };
};
