/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.net;

import java.io.*;
import java.util.*;

public class MultiPartMimeOutputStream extends java.io.DataOutputStream
{
    String boundary;
    boolean started = false;
    OutputStreamWriter writer;
    
    public MultiPartMimeOutputStream( OutputStream out, String boundary )
    {
	super( new BufferedOutputStream( out, 2048 ) );
	
	try
	    {
	    writer = new OutputStreamWriter( this, "UTF-8" );
	    }
	catch ( UnsupportedEncodingException e )
	    {
	    // can't happen !
	    }
	
	this.boundary = boundary;
    }
    
    public static String getBoundary()
    {
	int n = new Random().nextInt();
	return "---------------------------" + n;
    }
    
    public void writeField( String value, String name )
    throws IOException
    {
	if ( !started )
	{
	    writer.write( boundary );
	    writer.write( "\r\n" );
	}
	
	writer.write( "Content-Disposition: form-data; name=\"" );
	writer.write( name );
	writer.write( "\"\r\n");
	writer.write("Content-Type: text/plain\r\n\r\n");
	
	writer.write( value );
	
	writer.write( "\r\n" );
	writer.write( boundary );
	writer.write( "\r\n" );
	writer.flush();
    }
    
    public void writeFileIntro( String name, String file_name )
    throws IOException
    {
	if ( !started )
	{
	    writer.write( boundary );
	    writer.write( "\r\n" );
	}
	
	writer.write( "Content-Disposition: form-data; name=\"" );
	writer.write( name );
	writer.write( "\"" );
	if ( file_name != null )
	{
	    writer.write( " filename=\"" );
	    writer.write( file_name );
	    writer.write( "\"" );
	}
	writer.write( "\r\n");
	writer.write("Content-Type: application/binary\r\n\r\n");
	writer.flush();
	
/*
		byte[] buf = new byte[1024];
		int n;
		while ( (n = in.read( buf )) >=0 )
			{
			if ( n>0 )
				write( buf, 0, n );
			}
 */
    }
    
    public void writeBoundary()
    throws IOException
    {
	writer.write( "\r\n" );
	writer.write( boundary );
	writer.write( "\r\n" );
	writer.flush();
    }
    
}
