import { AnyOperation, TranModel } from "../persist";
import { Book, BookEventMap } from "./book";
import { applyOp } from "./op";

export type { BookEventMap };

export { Book };

export class Model {
  book: Book;

  constructor() {
    this.book = new Book();
  }

  appendHistory(model: TranModel) {
    this.book.appendHistory(model);
  }

  fromJSON(json: TranModel) {
    this.book.fromJSON(json);
  }

  toJSON(): TranModel {
    return this.book.toJSON();
  }

  serialize() {
    const clone = this.toJSON();
    return JSON.stringify(clone);
  }

  deserialize(jsonStr: string) {
    try {
      const json = JSON.parse(jsonStr);
      this.fromJSON(json);
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  applyOps(ops: AnyOperation[]) {
    const reverseOps: AnyOperation[] = [];
    ops.forEach(op => {
      const reverseOp = applyOp(this.book, op);
      reverseOps.unshift(reverseOp);
    });

    return reverseOps;
  }
}
