package jetbrains.mps.baseLanguage.editor;

/*Generated by MPS */

import jetbrains.mps.openapi.editor.EditorContext;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.openapi.editor.cells.EditorCell_Collection;
import jetbrains.mps.openapi.editor.cells.CellTraversalUtil;

public class CursorFocusUtils {
  public static void setCursorAfterModifierDeleted(EditorContext editorContext, SNode node, boolean backspace) {
    EditorCell currentCell = editorContext.getSelectedCell();
    EditorCell_Collection parent = currentCell.getParent();

    EditorCell cellToSelect = getNextCell(parent, currentCell, !(backspace));
    if (cellToSelect != null) {
      editorContext.selectWRTFocusPolicy(cellToSelect);
      if (!(backspace)) {
        // TODO: should we set caret to the end of cell if backspace ?
        cellToSelect.setCaretX(0);
      }
      return;
    } else if (!(backspace)) {
      // TODO: shold we do same process if backspace?
      // try cells one level up (needed only for methods when Delete)
      EditorCell_Collection parentParent = parent.getParent();
      cellToSelect = getNextCell(parentParent, parent, !(backspace));
      if (cellToSelect != null) {
        editorContext.selectWRTFocusPolicy(cellToSelect);
        cellToSelect.setCaretX(0);
        return;
      }
    }
    editorContext.selectWRTFocusPolicy(node);
  }

  private static EditorCell getNextCell(EditorCell_Collection parent, EditorCell anchorCell, boolean forward) {
    return (forward ? CellTraversalUtil.getNextSibling(anchorCell) : CellTraversalUtil.getPrevSibling(anchorCell));
  }
}
