package org.opengroupware.jope.appserver;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/*
 * THREAD: a response is not synchronized and can only be used from one
 *         thread w/o additional locking.
 */
public class WOResponse extends WOMessage implements WOActionResults {
  
  protected static int initialBufferSize = 4096;

  protected WORequest request = null;
  protected int       status  = WOMessage.HTTP_STATUS_OK;
  
  public WOResponse(WORequest _rq) {
    super();
    this.init(_rq);
  }
  
  protected void init(WORequest _rq) {
    super.init(_rq != null ? _rq.httpVersion() : null,
               null /* headers  */,
               null /* contents */,
               null /* userInfo */);
  
    this.request = _rq; // TODO: do we need to know that?
  
    this.outputStream = new ByteArrayOutputStream(initialBufferSize);
    this.outputWriter = new BufferedWriter
      (new OutputStreamWriter(this.outputStream));
    
    /* preconfigure for HTML */
    if (this.headers == null || !this.headers.containsKey("content-type"))
      this.setHeaderForKey("text/html; charset=iso-8859-1", "content-type");
  }
  
  /* accessors */
  
  public void setStatus(int _status) {
    this.status = _status;
  }
  public int status() {
    return this.status;
  }
  
  public WORequest request() {
    return this.request;
  }
  
  public void disableClientCaching() {
    // TODO: add expires header
    // TODO: maybe add some etag which changes always?
    // TODO: check whether those are correct
    this.setHeaderForKey("no-cache", "cache-control");
    this.setHeaderForKey("no-cache", "pragma");
  }
  
  /* WOActionResults */

  public WOResponse generateResponse() {
    return this;
  }
  
  /* streaming */
  
  public boolean enableStreaming() {
    // TODO: complete
    /* before streaming can be enabled, all HTTP headers need to be setup! */
    if (this.isStreaming())
      return true;
    
    OutputStream os = this.request.outputStream();
    if (os == null)
      return false;
    
    // TODO: setup HTTP stuff on ServletResponse prior writing!
    // TODO: write existing content to stream
    
    this.outputStream = os;
    this.outputWriter = new BufferedWriter
      (new OutputStreamWriter(this.outputStream));
    return true;
  }
}
