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

co.easimart.EasimartAddUniqueOperation Maven / Gradle / Ivy

package co.easimart;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * An operation that adds a new element to an array field, only if it wasn't already present.
 */
/** package */ class EasimartAddUniqueOperation implements EasimartFieldOperation {
  protected final LinkedHashSet objects = new LinkedHashSet<>();

  public EasimartAddUniqueOperation(Collection col) {
    objects.addAll(col);
  }

  @Override
  public JSONObject encode(EasimartEncoder objectEncoder) throws JSONException {
    JSONObject output = new JSONObject();
    output.put("__op", "AddUnique");
    output.put("objects", objectEncoder.encode(new ArrayList<>(objects)));
    return output;
  }

  @Override
  @SuppressWarnings("unchecked")
  public EasimartFieldOperation mergeWithPrevious(EasimartFieldOperation previous) {
    if (previous == null) {
      return this;
    } else if (previous instanceof EasimartDeleteOperation) {
      return new EasimartSetOperation(objects);
    } else if (previous instanceof EasimartSetOperation) {
      Object value = ((EasimartSetOperation) previous).getValue();
      if (value instanceof JSONArray || value instanceof List) {
        return new EasimartSetOperation(this.apply(value, null));
      } else {
        throw new IllegalArgumentException("You can only add an item to a List or JSONArray.");
      }
    } else if (previous instanceof EasimartAddUniqueOperation) {
      List previousResult =
          new ArrayList<>(((EasimartAddUniqueOperation) previous).objects);
      return new EasimartAddUniqueOperation((List) this.apply(previousResult, null));
    } else {
      throw new IllegalArgumentException("Operation is invalid after previous operation.");
    }
  }

  @Override
  public Object apply(Object oldValue, String key) {
    if (oldValue == null) {
      return new ArrayList<>(objects);
    } else if (oldValue instanceof JSONArray) {
      ArrayList old = EasimartFieldOperations.jsonArrayAsArrayList((JSONArray) oldValue);
      @SuppressWarnings("unchecked")
      ArrayList newValue = (ArrayList) this.apply(old, key);
      return new JSONArray(newValue);
    } else if (oldValue instanceof List) {
      ArrayList result = new ArrayList<>((List) oldValue);

      // Build up a Map of objectIds of the existing EasimartObjects in this field.
      HashMap existingObjectIds = new HashMap<>();
      for (int i = 0; i < result.size(); i++) {
        if (result.get(i) instanceof EasimartObject) {
          existingObjectIds.put(((EasimartObject) result.get(i)).getObjectId(), i);
        }
      }

      // Iterate over the objects to add. If it already exists in the field,
      // remove the old one and add the new one. Otherwise, just add normally.
      for (Object obj : objects) {
        if (obj instanceof EasimartObject) {
          String objectId = ((EasimartObject) obj).getObjectId();
          if (objectId != null && existingObjectIds.containsKey(objectId)) {
            result.set(existingObjectIds.get(objectId), obj);
          } else if (!result.contains(obj)) {
            result.add(obj);
          }
        } else {
          if (!result.contains(obj)) {
            result.add(obj);
          }
        }
      }
      return result;
    } else {
      throw new IllegalArgumentException("Operation is invalid after previous operation.");
    }
  }
}