package hirondelle.web4j.model;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/** General implementation of {@link MessageList}. */
public class MessageListImpl implements MessageList, Serializable {
  
  /** Create an empty {@link MessageList}.   */
  public MessageListImpl(){
    //empty 
  }

  /**
   Create a {@link MessageList} having one simple {@link AppResponseMessage}.
    
   <P>The argument satisfies the same conditions as {@link AppResponseMessage#forSimple}.
  */
  public MessageListImpl(String aMessage) {
    add(aMessage);
  }
  
  /**
   Create a {@link MessageList} having one compound {@link AppResponseMessage}.
   
   <P>The arguments satisfy the same conditions as 
   {@link AppResponseMessage#forCompound}.
  */
  public MessageListImpl(String aMessage, Object... aParams) {
    add(aMessage, aParams);
  }
  
  public final void add(String aMessage){
    fAppResponseMessages.add(AppResponseMessage.forSimple(aMessage));
  }
  
  public final void add(String aMessage, Object... aParams){
    fAppResponseMessages.add(AppResponseMessage.forCompound(aMessage, aParams));
  }
  
  public final void add (AppException ex) {
    fAppResponseMessages.addAll( ex.getMessages() );
  }
  
  public final List<AppResponseMessage> getMessages () {
    return Collections.unmodifiableList(fAppResponseMessages);
  }
  
  public final boolean isNotEmpty () {
    return !isEmpty();
  }
  
  public final boolean isEmpty () {
    return fAppResponseMessages.isEmpty();
  }
  
  /** Intended for debugging only.  */
  @Override public String toString(){
    return 
      "Messages : + " + fAppResponseMessages.toString() + 
      " Has Been Displayed  : " +  fHasBeenDisplayed
    ;
  }
  
  // PRIVATE 
  
  /** List of {@link AppResponseMessage}s attached to this exception.  */
  private final List<AppResponseMessage> fAppResponseMessages = new ArrayList<AppResponseMessage>();
  
  /** Controls the display-once-only behavior needed for JSPs.  */
  private boolean fHasBeenDisplayed = false;
  
  private static final long serialVersionUID = 1000L;
  
   /** Always treat de-serialization as a full-blown constructor, by validating the final state of the deserialized object. */
  private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException {
    aInputStream.defaultReadObject();
  }
}
