package jetbrains.mps.internal.make.runtime.util;

/*Generated by MPS */

import org.jetbrains.mps.annotations.Immutable;
import jetbrains.mps.annotations.GeneratedClass;
import java.util.Objects;
import java.util.Arrays;

/**
 * Hierarchical delta identity, capable to answer questions like [a/b/c].contains([a/b/c/d])
 * and [a/b/c].commonPrefix([a/b/d/e]).
 * Leftmost component in key array is most generic, rightmost is most specific.
 */
@Immutable
@GeneratedClass(node = "r:f8580193-afc4-4673-a635-d4757ca591cf(jetbrains.mps.internal.make.runtime.util)/6192537294411385", model = "r:f8580193-afc4-4673-a635-d4757ca591cf(jetbrains.mps.internal.make.runtime.util)")
public final class DeltaKey {
  private final Object[] myKey;

  public DeltaKey(Object... key) {
    // for safety, may want to copy array (with distinct copy cons for internal uses)
    // however, expect this class to be used from within MPS only, by qualified developers that
    // in most cases would pass just a list of values (not Object[]), and even if they pass Object[], they won't modify in afterwards
    myKey = key;
  }

  public DeltaKey commonPrefix(DeltaKey other) {
    int commonLength = 0;
    for (; commonLength < Math.min(myKey.length, other.myKey.length); commonLength++) {
      if (!(Objects.equals(myKey[commonLength], other.myKey[commonLength]))) {
        break;
      }
    }
    return new DeltaKey(Arrays.copyOfRange(myKey, 0, commonLength));
  }

  public boolean isEmpty() {
    return myKey == null || myKey.length == 0;
  }

  public boolean contains(DeltaKey other) {
    if (other.myKey.length < myKey.length) {
      return false;
    }
    for (int i = 0; i < myKey.length; i++) {
      if (!(Objects.equals(myKey[i], other.myKey[i]))) {
        return false;
      }
    }
    return true;
  }

  @Override
  public int hashCode() {
    return Arrays.hashCode(myKey);
  }
  @Override
  public boolean equals(Object o) {
    return (o instanceof DeltaKey ? Arrays.equals(myKey, ((DeltaKey) o).myKey) : false);
  }
}
