import { ActionHandleStrategy } from '../../../dto/action-handle-strategies/action-handle-strategy.abstract';
import { RemoveChildrenAction } from '../../../dto/actions/remove-child-action';
import { CreateSegmentTableCellAction } from '../actions/create-segment-table-cell-action';
/**
 * Strategy to split a partially overlapped table cell.
 */
export class SplitTableCellStrategy extends ActionHandleStrategy {
  /**
   * @inheritDoc
   */
  handleAction(action, row) {
    const { table, cell, col, cellStartCol, endCol, targetCellType } = action.payload;
    const cellEndCol = cellStartCol + cell.colSpan - 1;
    const leftColSpan = col > cellStartCol ? col - cellStartCol : 0;
    const overlapEndCol = Math.min(endCol, cellEndCol);
    const middleColSpan = overlapEndCol - col + 1;
    const rightColSpan = cellEndCol - overlapEndCol;
    if (leftColSpan > 0) {
      row.apply(new CreateSegmentTableCellAction({
        table,
        sourceCell: cell,
        colSpan: leftColSpan,
        cellType: cell.type,
        keepSourceContent: true,
      }));
    }
    row.apply(new CreateSegmentTableCellAction({
      table,
      sourceCell: cell,
      colSpan: middleColSpan,
      cellType: targetCellType,
      keepSourceContent: leftColSpan === 0,
    }));
    if (rightColSpan > 0) {
      row.apply(new CreateSegmentTableCellAction({
        table,
        sourceCell: cell,
        colSpan: rightColSpan,
        cellType: cell.type,
        keepSourceContent: leftColSpan === 0 && middleColSpan === cell.colSpan,
      }));
    }
    row.apply(new RemoveChildrenAction(cell));
  }
}
