import { AppendChildrenAction } from '../../actions/append-child-nodes-action';
import { InsertChildrenAfterAction } from '../../actions/insert-children-after-block';
import { RemoveChildrenAction } from '../../actions/remove-child-action';
import { SyncUpSelectionAction } from '../../actions/sync-up-selection-action';
import { ActionHandleStrategy } from '../action-handle-strategy.abstract';
/**
 * Convert the selected blocks to list strategy.
 */
export class ListTransformToListStrategy extends ActionHandleStrategy {
  /**
   * @inheritDoc
   */
  handleAction(action, target) {
    const selectedBlocks = action.selectedBlocks;
    const bulletList = target.parent.createList(action.listType);
    const isSameList = selectedBlocks.every((block) => block.parent === target);
    if (isSameList) {
      // Select one or more list items belonging to the same list, and all items in this list should be updated
      bulletList.apply(new AppendChildrenAction(target.children));
      target.parent.apply(new InsertChildrenAfterAction(target, bulletList));
      target.parent.apply(new RemoveChildrenAction(target));
      selectedBlocks.forEach((block) => block.children.map((node) => node.apply(new SyncUpSelectionAction())));
    }
    else {
      const listItems = action.selectedBlocks.map((block) => target.parent.toListItem(block));
      bulletList.apply(new AppendChildrenAction(listItems));
      target.parent.apply(new InsertChildrenAfterAction(target, bulletList));
      action.selectedBlocks.forEach((block) => {
        block.parent.apply(new RemoveChildrenAction(block));
      });
      if (target.children.length === 0) {
        target.parent.apply(new RemoveChildrenAction(target));
      }
    }
  }
}
