import { Plugin } from "prosemirror-state";
import { EditorSchema } from "../schema";
import { PluginDescriptor } from "../util/PluginDescriptor";

export interface PluginState {
  readonly editable: boolean;
}

const { key, getPluginState, getPluginStateOrThrow, setPluginState } = new PluginDescriptor<PluginState>("EditablePlugin");
export { getPluginStateOrThrow, setPluginState };

export class EditablePlugin extends Plugin<EditorSchema> {
  constructor(defaultEditable: boolean) {
    super({
      key,

      state: {
        init: (): PluginState => ({
          editable: defaultEditable
        }),
        apply(tr, cur: PluginState): PluginState {
          const nextPluginState = getPluginState(tr);
          return nextPluginState !== null ? nextPluginState : cur;
        }
      },

      props: {
        editable: state => {
          const { editable } = getPluginStateOrThrow(state);
          return editable;
        }
      }
    });
  }
}
