/* ======================================================================
   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.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 );
			}
		}

	}
