// ============================================================================
// File:               $File$
//
// Project:
//
// Purpose:
//
// Author:             Rammi
//
// Copyright Notice:   (c) 1999-2006  Rammi (rammi@caff.de)
//                     This code is in the public domain.
//                     Use at own risk.
//                     No guarantees given.
//
// Latest change:      $Date: 2006-02-01 13:48:49 +0100 (Mi, 01 Feb 2006) $
//
// History:	       $Log$
//=============================================================================

package de.caff.util.debug;

import java.io.OutputStream;


/**
 *  An OutputStream, which sends all output to the debugging interface.
 *  Used to capture the standard streams from System.
 *
 *  @see Debug
 *
 *  @author Rammi
 */
public class DebuggingOutputStream
        extends OutputStream
{
  /** Constant for the stdout stream */
  static final int STDOUT = 0;
  /** Constant for the stderr stream. */
  static final int STDERR = 1;

  private int  _direction;

  /**
   *  Constructor.
   *  @param  dir  <code>STDOUT</code> or <code>STDERR</code>
   */
  DebuggingOutputStream(int dir) {
    _direction = dir;
  }

  /**
   *  Forward a string to the debug interface.
   *  @param str   message to be forwarded
   */
  private void write(String str) {
    switch (_direction) {
    case STDOUT:
      Debug.writeStdoutMessage(str);
      break;

    case STDERR:
      Debug.writeStderrMessage(str);
      break;
    }      
  }

  /**
   *  Close stream. Does nothing.
   */
  public void close() {
    // empty
  }
  
  /**
   *  Flush stream. Does nothing.
   */
  public void flush() {
    // empty
  }

  /**
   *  Write a byte.
   *  @param b  the byte
   */
  public void write(int b) {
    byte[] bytes = new byte[1];
    bytes[0] = (byte)(b&0xFF);
    write(new String(bytes));
  }

  /**
   *  Write a byte array.
   *  @param b  the byte array
   */
  public void write(byte[] b) {
    write(new String(b));
  }

  /**
   *  Write a part of a byte array.
   *  @param b    the byte array
   *  @param off  start offset to first byte to be written
   *  @param len  number of bytes to write
   */
  public void write(byte[] b, int off, int len) {
    write(new String(b, off, len));
  }
}
