import Command from "@ckeditor/ckeditor5-core/src/command";
import {findOptimalInsertionPosition} from "@ckeditor/ckeditor5-widget/src/utils";
import {createColumnLayout} from "./columns";

export default class LayoutColumnCommand extends Command
{
  constructor(editor)
  {
    super(editor);

    // Remove default document listener to lower its priority.
    this.stopListening(this.editor.model.document, 'change');

    // Lower this command listener priority to be sure that refresh() will be called after link & image refresh.
    this.listenTo(this.editor.model.document, 'change', () => this.refresh(), {priority: 'lowest'});
  }

  refresh()
  {
    const imageCommand = this.editor.commands.get('imageInsert');
    const linkCommand = this.editor.commands.get('link');

    // The filer command is enabled when one of imageInsert or link command is enabled.
    this.isEnabled = (imageCommand && imageCommand.isEnabled) || (linkCommand && linkCommand.isEnabled);
  }

  execute(a)
  {
    const model = this.editor.model;
    const selection = model.document.selection;

    const insertPosition = findOptimalInsertionPosition(selection, model);
    model.change(
      writer =>
      {
        createColumnLayout(writer, insertPosition, a);
      }
    );
  }
}
