package org.basex.query.up.primitives;

import org.basex.data.Data;
import org.basex.query.iter.NodeCache;
import org.basex.util.InputInfo;

/**
 * Insert before primitive.
 *
 * @author BaseX Team 2005-12, BSD License
 * @author Lukas Kircher
 */
public final class InsertBefore extends InsertBase {
  /**
   * Constructor.
   * @param p pre
   * @param d data
   * @param i input info
   * @param c node copy
   */
  public InsertBefore(final int p, final Data d, final InputInfo i,
      final NodeCache c) {
    super(PrimitiveType.INSERTBEFORE, p, d, i, c);
  }

  @Override
  public void apply() {
    super.apply();
    data.insert(pre, data.parent(pre, data.kind(pre)), md);
  }

  @Override
  public boolean adjacentTexts(final int c) {
    final int p = pre + c;
    boolean merged = false;
    final int mds = md.meta.size;
    if(md.kind(0) == Data.TEXT)
      merged = mergeTexts(data, p - 1, p);
    if(!merged && md.kind(mds - 1) == Data.TEXT)
      merged |= mergeTexts(data, p + mds - 1, p + mds);

    return merged;
  }
}

@@ -298,14 +298,211 @@
 e %7B%0A
+  /** Parent of node to be inserted. Need to cache this as delete and replace%0A   * primitives (which are executed before insert before) mess with parent%0A   * values.%0A   */%0A  private final int par;%0A
   /**%0A
-
    *
@@ -753,16 +753,50 @@
  i, c);%0A
+    par = d.parent(p, d.kind(p));%0A
   %7D%0A%0A  @
@@ -872,40 +872,11 @@
 re, 
-data.parent(pre, data.kind(pre))
+par
 , md

replace and delete primitives mess with parent value of insert before if applied on the same target. Fixed by caching the parent value for all insert before primitives.