All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.avos.avoscloud.ops.RemoveOp Maven / Gradle / Ivy

package com.avos.avoscloud.ops;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.avos.avoscloud.AVUtils;

public class RemoveOp extends CollectionOp {

  private Set values = new HashSet();

  public RemoveOp(String key, Collection values) {
    super(key, OpType.Remove);
    if (values != null) {
      for (Object obj : values) {
        this.values.add(obj);
      }
    }
  }

  public RemoveOp() {
    super();
  }

  public Set getValues() {
    return values;
  }

  @Override
  public Map encodeOp() {
    return AVUtils.createArrayOpMap(key, "Remove", this.getParsedValues());
  }

  @Override
  public Object apply(Object oldValue) {
    List result = new LinkedList();
    if (oldValue != null) {
      result.addAll((Collection) oldValue);
    }
    if (getValues() != null) {
      result.removeAll(getValues());
    }
    return result;
  }

  @Override
  public AVOp merge(AVOp other) {
    assertKeyEquals(other);
    switch (other.type()) {
      case Null:
        return this;
      case Set:
        return other;
      case Remove:
        this.values.addAll(other.cast(RemoveOp.class).values);
        return this;
      case AddUnique:
      case Add:
      case AddRelation:
      case RemoveRelation:
        return new CompoundOp(key, this, other);
      case Increment:
        throw new UnsupportedOperationException("Could not increment an non-numberic value.");
      case Delete:
        return other;
      case Compound:
        other.cast(CompoundOp.class).addFirst(this);
        return other;
      default:
        throw new IllegalStateException("Unknow op type " + other.type());
    }
  }
}