package bigloo;

import java.io.*;

public class output_port extends obj
{
  public OutputStream out;
  public byte[] name = "???".getBytes();

  public output_port( final OutputStream  stream )
  {
    out= stream;
  }

  public output_port( final OutputStream  stream, final byte[] _name)
  {
    name= _name;
    out= stream;
  }

  public output_port( final byte[]  file )
      throws IOException
  {
    // CARE JVM dependant ?!
    this( new FileOutputStream( foreign.bigloo_strcmp( file, "null:".getBytes() )
                                ? (foreign.bigloo_strcmp( os.OS_CLASS, "unix".getBytes() )
                                   ? "/dev/null"
                                   : "NUL:")
                                : new String( file ) ) );
    // this( new BufferedOutputStream( new FileOutputStream( new String( file ) ) ) );
    name = file;
  }

  public output_port( final byte[]   file,
                      final boolean  append )
    throws IOException
  {
    // CARE JVM dependant ?!
    this( new FileOutputStream( new String( file ), append ) );
    name= file;
  }

  public Object close()
  {
    try
    {
      out.close();
    }
    catch (final Exception e)
    {
      if (out == null)
	 return bigloo.foreign.BUNSPEC;
      else
	 foreign.fail( "close", e.getMessage(), this );
    }

    return this;
  }

  public Object flush()
  {
    try
    {
      out.flush();
      return bbool.vrai;
    }
    catch (final Exception e)
    {
      if (out != null)
        foreign.fail( "flush", e.getMessage(), this );
      return bbool.faux;
    }
  }

  public Object bgl_output_port_seek( final int  pos )
    throws IOException
  {
    return bigloo.foreign.BFALSE;
  }

  public final void write( final int  cn )
  {
    try
    {
      out.write( cn );
    }
    catch (final Exception e)
    {
      if (out != null)
        foreign.fail( "write", e.getMessage(), this );
    }
  }

  public final void write( final byte[]  s )
  {
    try
    {
      out.write( s, 0, s.length );
    }
    catch (final Exception e)
    {
      if (out != null)
        foreign.fail( "write", e.getMessage(), this );
    }
  }

  public final void write( final String  s )
  {
    try
    {
      final int         len= s.length();

      for ( int i= 0 ;i < len ; ++i )
        out.write( (byte)s.charAt( i ) );
    }
    catch (final Exception e)
    {
      if (out != null)
        foreign.fail( "write", e.getMessage(), this );
    }
  }

  public void write( final output_port  p )
  {
    p.write( "#<output_port:" + new String( name ) + ">" );
  }
}
