import {Command} from 'ckeditor5/src/core';

export default class InsertMapEmbedCommand extends Command {
  execute(settings) {
    const { model } = this.editor;

    model.change((writer) => {
      model.insertContent(createMapEmbed(writer, settings.map, settings.map_title, settings.show_description));
    });
  }

  refresh() {
    const { model } = this.editor;
    const { selection } = model.document;

    const allowedIn = model.schema.findAllowedParent(selection.getFirstPosition(), 'simpleMap');
    this.isEnabled = allowedIn !== null;
  }
}

function createMapEmbed(writer, mapId, mapTitle, showDescription) {
  const mapEmbed = writer.createElement('simpleMap');

  writer.setAttribute('mapId', mapId, mapEmbed);
  writer.setAttribute('mapTitle', mapTitle, mapEmbed);
  writer.setAttribute('showDescription', showDescription === 1, mapEmbed);

  return mapEmbed;
}
