/* ======================================================================
The Bodington System Software License, Version 1.0
  
Copyright (c) 2001 The University of Leeds.  All rights reserved.
  
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1.  Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2.  Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3.  The end-user documentation included with the redistribution, if any,
must include the following acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.

4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.

5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES 
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO 
EVENT SHALL THE UNIVERSITY OF LEEDS OR ITS CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
=========================================================

This software was originally created by the University of Leeds and may contain voluntary 
contributions from others.  For more information on the Bodington Open Source Project, please 
see http://bodington.org/

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

package org.bodington.applet.components;

import org.bodington.applet.components.*;
import org.bodington.net.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;


public abstract class TransferDataDialog extends org.bodington.applet.components.ProgressDialog
	{
	LoginDialog login_dialog;
	MultiPartMimeOutputStream multi_out=null;
	PostOutput post_out=null;
	HttpURLConnection httpcon=null;
	//int chunk_size;
	
	
	public TransferDataDialog( JDesktopPane desktop, String title, String message, boolean can_cancel )
		{
		super( desktop, title, message, can_cancel );
		} 
		
	public void startGet( URL url )
		throws IOException
		{
		startGetOrPost( url, false );
		}
		
	public void startPost( URL url )
		throws IOException
		{
		startGetOrPost( url, true );
		}
		
	public void startGetOrPost( URL url, boolean post )
		throws IOException
		{
		setMessage( "Requesting data" );
		setProgress( 0 );
		if ( login_dialog == null )
			{
			login_dialog = new LoginDialog();
			login_dialog.setModal( true );
			}

		validate();
		
        httpcon = (HttpURLConnection)url.openConnection();

		// stop if user cancelled login
		if ( !login_dialog.login( httpcon ) )
			throw new IOException( "User Cancelled Login" );

        httpcon.setDoOutput( post );
        httpcon.setRequestMethod( post?"POST":"GET");
        }
        
    public void postField( String name, String value )
		throws IOException
        {
        if ( post_out == null )
            {
            post_out = new PostOutput( httpcon.getOutputStream() );
            }
        else
            post_out.write( (byte)'&' );
            
        String uname = URLEncoder.encode( name, "UTF-8" );
        byte[] bname = uname.getBytes();
        post_out.write( bname );
        post_out.write( (byte)'=' );
        String uvalue = URLEncoder.encode( value, "UTF-8" );
        byte[] bvalue = uvalue.getBytes();
        post_out.write( bvalue );
        }
        
	public void startMultiPartPost( URL url )
		throws IOException
		{
		setMessage( "Preparing to Send Data" );
		setProgress( 0 );
		if ( login_dialog == null )
			{
			login_dialog = new LoginDialog();
			login_dialog.setModal( true );
			}

		validate();
		
        httpcon = (HttpURLConnection)url.openConnection();

		// stop if user cancelled login
		if ( !login_dialog.login( httpcon ) )
			throw new IOException( "User Cancelled Login" );

      httpcon.setDoOutput( true );
      httpcon.setRequestMethod("POST");

		String boundary = MultiPartMimeOutputStream.getBoundary();
      httpcon.setRequestProperty( "Content-type", "multipart/form-data; boundary=" + boundary );

	   multi_out = new MultiPartMimeOutputStream( httpcon.getOutputStream(), boundary );
		}
		
	public OutputStream getPartOutputStream( String file_name, long size )
		throws IOException
		{
		if ( file_name !=null )
			setMessage( "Sending " + file_name );
		else
			setMessage( "Sending Data" );
		setProgress( 0 );
		
		return new PartOutput( multi_out, file_name, size );
		}

	public InputStream getResponse()
		throws IOException
		{
		setMessage( "Getting Response" );
		setProgress( 0 );

        if ( post_out != null )
            {
            post_out.close();
            post_out = null;
            }
        
        if ( multi_out != null )
            {
    		multi_out.close();
		    multi_out = null;
		    }
		
		return new ResponseInput( httpcon.getInputStream(), httpcon.getContentLength() ); 
		}
	
	public class PostOutput extends OutputStream
		{
		OutputStream real_out;
		int chunk_size;
		long written;
		
		public PostOutput( OutputStream out )
			throws IOException
			{
			real_out = out;
			written = 0;
		    chunk_size = 128;
			}
			
		public void close() throws IOException
			{
			real_out.close();
			}
			
		public void flush() throws IOException
			{
			real_out.flush();
			}

		public void write( byte[] b, int off, int len ) throws IOException
			{
			int o=off, l=len, chunk;
			
			//break into 1k chunks if bigger than that
			for ( int i=off; i<(off+len); i+=chunk_size )
				{
				// if there's more than 1k left send 1k
				// otherwise send all that's left
				chunk = (len-(i-off)) > chunk_size  ?  chunk_size : (len-(i-off));
				real_out.write( b, i, chunk );
				written+=chunk;
				
				// progress bar repeatedly sweeps out 10k blocks
				// if we don't know the size of the output
				setProgress( (int)((written/chunk_size)%10L)*10 );
				Thread.yield();
				}
			}

		public void write( byte[] b ) throws IOException
			{
			write( b, 0, b.length );
			}

		public void write( int b ) throws IOException
			{
			real_out.write( b );
			written++;
			
			if ( written%chunk_size == 0 )
				{
				// progress bar repeatedly sweeps out 10k blocks
				// if we don't know the size of the output
				setProgress( (int)((written/chunk_size)%10)*10 );
				Thread.yield();
				}
				
			}

		}
	
	
	public class PartOutput extends OutputStream
		{
		MultiPartMimeOutputStream real_out;
		int chunk_size;
		long size;
		long written;
		
		public PartOutput( MultiPartMimeOutputStream out, String file_name, long size )
			throws IOException
			{
			real_out = out;
			if ( file_name!=null )
				real_out.writeFileIntro( "file", file_name );
			this.size = size;
			written = 0;

		    chunk_size = 1024;
        		
		    if ( size<(10*1024) )
			    chunk_size = 128;
			}
			
		public void close() throws IOException
			{
			real_out.writeBoundary();
			}
			
		public void flush() throws IOException
			{
			real_out.flush();
			}

		public void write( byte[] b, int off, int len ) throws IOException
			{
			int o=off, l=len, chunk;
			
			//break into 1k chunks if bigger than that
			for ( int i=off; i<(off+len); i+=chunk_size )
				{
				// if there's more than 1k left send 1k
				// otherwise send all that's left
				chunk = (len-(i-off)) > chunk_size  ?  chunk_size : (len-(i-off));
				real_out.write( b, i, chunk );
				written+=chunk;
				
				if ( size > 0 && written <= size )
					{
					// update progress bar
					setProgress( (int)(100.0 * (double)written / (double)size ) );
					Thread.yield();
					}
				else
					{
					// progress bar repeatedly sweeps out 10k blocks
					// if we don't know the size of the output
					setProgress( (int)((written/chunk_size)%10L)*10 );
					Thread.yield();
					}
				}
			}

		public void write( byte[] b ) throws IOException
			{
			write( b, 0, b.length );
			}

		public void write( int b ) throws IOException
			{
			real_out.write( b );
			written++;
			
			if ( written%chunk_size == 0 )
				{
				if ( size > 0 && written <= size )
					{
					// update progress bar
					setProgress( (int)(100.0 * (double)written / (double)size ) );
					Thread.yield();
					}
				else
					{
					// progress bar repeatedly sweeps out 10k blocks
					// if we don't know the size of the output
					setProgress( (int)((written/chunk_size)%10)*10 );
					Thread.yield();
					}
				}
				
			}

		}
	
	
	public class ResponseInput extends InputStream
		{
		InputStream real_in;
		int chunk_size, size, read;
		
		public ResponseInput( InputStream in, int size )
			{
			real_in = in;
			this.size = size;
			read=0;

		    chunk_size = 1024*64;
        		
		    if ( size<(256*1024) )
			    chunk_size = 1024*8;
			}
		
		public int read() throws IOException
			{
			if ( read%chunk_size == 0 )
				{
				if ( size > 0 && read <= size )
					{
					// update progress bar
					setProgress( (int)(100.0 * (double)read / (double)size ) );
					//Thread.yield();
					}
				else
					{
					// progress bar repeatedly sweeps out 10k blocks
					// if we don't know the size of the output
					setProgress( (int)((read/chunk_size)%10)*10 );
					//Thread.yield();
					}
				}
				
			return real_in.read();
			}
			
		public int read(byte[] b) throws IOException
			{
			return read( b, 0, b.length );
			}

		public int read(byte[] b, int off, int len) throws IOException
			{
			int o=off, l=len, chunk, received, total=0;
			
			//break into chunks if bigger than that
			for ( int i=off; i<(off+len); i+=received )
				{
				// if there's more than chunk_size left send chunk_size
				// otherwise send all that's left
				chunk = (len-(i-off)) > chunk_size  ?  chunk_size : (len-(i-off));
				
				received = real_in.read( b, i, chunk );
				if ( received == -1 )
					return total==0?-1:total;
				
				total += received;
				
				read+=chunk;
				
				if ( size > 0 && read <= size )
					{
					// update progress bar
					setProgress( (int)(100.0 * (double)read / (double)size ) );
					//Thread.yield();
					}
				else
					{
					// progress bar repeatedly sweeps out 10k blocks
					// if we don't know the size of the output
					setProgress( ((read/chunk_size)%10)*10 );
					//Thread.yield();
					}
				}
				
			return total;
			}
			
		public int available() throws IOException
			{
			return real_in.available();
			}
			
		public void close() throws IOException
			{
			real_in.close();
			}
			
		public synchronized void mark(int readlimit)
			{
			real_in.mark( readlimit );
			}

		public boolean markSupported()
			{
			return real_in.markSupported();
			}
			
		public long skip(long n) throws IOException
			{
			return real_in.skip( n );
			}
		}

	}
