import changeManager from '../../../../../helpers/change-manager/change-manager';
import domNodeSubjectFactory from '../../../../../helpers/change-manager/subject/dom-node-subject/dom-node-subject-factory';
import { VegaInternalRichTextEditorSelectionRangeChange } from '../../../../../helpers/event-manager/event-id/vega-internal-event-id';
import { generateUUID } from '../../../../../utils/misc';
import stateEntityRenderingRegistry from '../../../slimmers/controllers/state-entity-rendering-registry';
import { InsertChildrenAfterAction } from '../../actions/insert-children-after-block';
import { UpdateCodeBlockAction } from '../../actions/update-code-block-action';
import { RTETextBlock } from '../../blocks/text-block';
import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
/**
 * Remove the line break and insert new paragraph after code block.
 */
export class SwitchOutFromCodeBlockStrategy extends ActionHandleStrategy {
  /**
   * @inheritDoc
   */
  handleAction(action, target) {
    const { content, language } = action;
    const textArray = content.split('\n');
    const updateAction = new UpdateCodeBlockAction(textArray.slice(0, textArray.length - 2).join('\n'), language);
    updateAction.isFlushable = false;
    target.children[0].apply(updateAction);
    const textBlock = RTETextBlock.from({
      id: generateUUID(),
      type: 'paragraph',
      nodes: [{ id: generateUUID(), text: '', type: 'text' }],
    });
    target.parent.apply(new InsertChildrenAfterAction(target, textBlock));
    // Focus the next text node after value update.
    const currentNodeDom = stateEntityRenderingRegistry.getDOMByEntity(target);
    if (currentNodeDom) {
      const nodeSubject = domNodeSubjectFactory.getSubjectFromParentNodeByEventId(currentNodeDom, VegaInternalRichTextEditorSelectionRangeChange);
      if (nodeSubject) {
        changeManager.notify(nodeSubject, { node: textBlock.children[0] });
      }
    }
  }
}
