package org.activiti.engine.impl.persistence.entity;

import java.io.Serializable;

import org.activiti.engine.impl.context.Context;

/**
 * <p>Encapsulates the logic for transparently working with {@link ByteArrayEntity}.</p>
 * 
 * <p>Make sure that instance variables (i.e. fields) of this type are always initialized, 
 * and thus <strong>never</strong> null.</p>
 * 
 * <p>For example:</p>
 * <pre>
 * private final ByteArrayRef byteArrayRef = new ByteArrayRef();
 * </pre>
 * 
 * @author Marcus Klimstra (CGI)
 */
public final class ByteArrayRef implements Serializable {
  
  private static final long serialVersionUID = 1L;
  
  private String id;
  private String name;
  private ByteArrayEntity entity;
  
  public ByteArrayRef() {
  }

  // Only intended to be used by ByteArrayRefTypeHandler
  public ByteArrayRef(String id) {
    this.id = id;
  }
  
  public String getId() {
    return id;
  }
  
  public String getName() {
    return name;
  }
  
  public byte[] getBytes() {
    ensureInitialized();
    return (entity != null ? entity.getBytes() : null);
  }
  
  public void setValue(String name, byte[] bytes) {
    this.name = name;
    setBytes(bytes);
  }
  
  private void setBytes(byte[] bytes) {
    if (id == null) {
      if (bytes != null) {
        entity = ByteArrayEntity.createAndInsert(name, bytes);
        id = entity.getId();
      }
    }
    else {
      ensureInitialized();
      entity.setBytes(bytes);
    }
  }
  
  public ByteArrayEntity getEntity() {
    ensureInitialized();
    return entity;
  }

  public void delete() {
    if (id != null) {
      if (entity != null) {
        // if the entity has been loaded already,
        // we might as well use the safer optimistic locking delete.
        Context.getCommandContext()
        .getByteArrayEntityManager()
        .deleteByteArray(entity);
      }
      else {
        Context.getCommandContext()
          .getByteArrayEntityManager()
          .deleteByteArrayById(id);
      }
      id = null;
      entity = null;
      name = null;
    }
  }
  
  private void ensureInitialized() {
    if (id != null && entity == null) {
      entity = Context.getCommandContext()
        .getByteArrayEntityManager()
        .findById(id);
      name = entity.getName();
    }
  }

  @Override
  public String toString() {
    return "ByteArrayRef[id=" + id + ", name=" + name + ", entity=" + entity + "]";
  }
}

@@ -704,24 +704,59 @@
 y entity;%0A  
+protected boolean deleted = false;%0A
 %0A  public By
@@ -1608,26 +1608,24 @@
     if (
-id != null
+!deleted
 ) %7B%0A    
@@ -2024,57 +2024,22 @@
     
-id = null;%0A      entity = null;%0A      name = null
+deleted = true
 ;%0A  
@@ -2271,16 +2271,72 @@
  %7D%0A  %7D%0A%0A
+  public boolean isDeleted() %7B%0A    return deleted;%0A  %7D%0A%0A
   @Overr
@@ -2451,11 +2451,37 @@
 y + 
+(deleted ? %22, deleted%5D%22 :
 %22%5D%22
+)
 ;%0A  

delete flag for ByteArrayRef