import WidgetHelper from "../widget-helper";

export default class LayoutEditable extends WidgetHelper
{
  _schemaName()
  {
    return 'layout-editable';
  }

  _schemaDefinition()
  {
    return {
      inheritAllFrom: ['$text', '$block'],
      isLimit: true
    };
  }

  init()
  {
    super.init();
    const model = this.editor.model;
    //model.schema.extend('$text', {allowIn: 'layout-editable'});
    model.schema.extend('$block', {allowIn: 'layout-editable'});

    const conversion = this.editor.conversion;
    conversion.for('upcast').elementToElement(
      {
        view: {
          name: 'div',
          classes: ['ck-layout-editable']
        },
        model: 'layout-editable'
      }
    );

    conversion.for('dataDowncast').elementToElement(
      {
        model: this._schemaName(),
        view: (modelItem, viewWriter) =>
        {
          return viewWriter.createContainerElement('div', {class: 'ck-layout-editable'});
        }
      }
    );

    conversion.for('editingDowncast').elementToElement(
      {
        model: this._schemaName(),
        view: (modelItem, viewWriter) =>
        {
          const widgetElement = viewWriter.createEditableElement('div', {class: 'ck-layout-editable'});
          // Enable widget handling on placeholder element inside editing view.
          return this._toWidgetEditable(widgetElement, viewWriter);
        }
      }
    );
  }
}

export function createLayoutEditable(writer, layout)
{
  writer.createElement('layout-editable');
  let editable = writer.createElement('layout-editable');
  let paragraph = writer.createElement('paragraph');
  writer.insert(paragraph, writer.createPositionAt(editable, 'end'));
  writer.insert(editable, writer.createPositionAt(layout, 'end'));
}
