package org.bodington.util;

import java.io.*;

public class RolloverFileOutputStream extends java.io.OutputStream
	{
	String folder, prefix, suffix;
	
	FileOutputStream current;
	int n;
	int length;
	
	boolean rollover_pending;
	
	public RolloverFileOutputStream( String folder, String prefix, String suffix )
		{
		this.folder = folder;
		this.prefix = prefix;
		this.suffix = suffix;
		n= 1000;
		try
			{
			nextFile();
			}
		catch ( IOException ex )
			{
			throw new NullPointerException( "Unable to create first rollover file." );
			}
		}
	
    public void write(int b) throws IOException
    	{
    	if ( current == null )
    		throw new IOException( "Next rollover file can't be opened." );

    	current.write( b );
    	
    	length++;
    	if ( length > 1024*1024*5 )
    		rollover_pending = true;
    		
    	if ( rollover_pending && b == '\n' )
    		nextFile();
        // This method is derived from class java.io.OutputStream
        // to do: code goes here
    	}

	private void nextFile() throws IOException
		{
		if ( current != null )
			{
			current.flush();
			current.close();
			}
		
		current = null;
		length = 0;
		rollover_pending = false;
		File f;
		for ( ; true; n++ )
			{
			String name = folder + File.separator + prefix + n + suffix;
			f = new File( name );
			if ( !f.exists() )
				{
				current = new FileOutputStream( f );
				return;
				}
			}
		}
	
	public void flush() throws IOException
		{
    	if ( current == null )
    		throw new IOException( "Next rollover file can't be opened." );
		current.flush();
		}

	public void close() throws IOException
		{
    	if ( current == null )
    		throw new IOException( "Next rollover file can't be opened." );
		current.close();
		}
	}
