/* ======================================================================
   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 java.awt.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import org.w3c.dom.Document;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;

import javax.xml.transform.dom.DOMSource; 

import javax.xml.transform.stream.StreamResult; 
public class TransferManifestDialog extends org.bodington.applet.components.TransferDataDialog
	implements Runnable
	{
	Document xml;
	URL url;
	Thread worker=null;
	
	public TransferManifestDialog( JDesktopPane desktop )
		{
		super( desktop, "Uploading Manifest", "Preparing to Upload Manifest", true );
		}
	public void transfer( Document xml, URL url )
		throws IOException
		{
		if ( worker!=null )
			throw new IOException( "Transfer already in progress." );
		
		this.xml = xml;
		this.url = url;
		worker = new Thread( this );
		worker.start();
		
		show();
		
		if ( worker!=null )
			{
			worker.stop();
			worker = null;
			}
		}
		
	public void run()
		{
		try
			{
			startMultiPartPost( url );
			OutputStream out = getPartOutputStream( "imsmanifest.xml", -1 );
		// NOTE: in XLST parlance this is an 'identity' transformation.
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer transformer = factory.newTransformer();
		DOMSource source = new DOMSource(xml);
		StreamResult result = new StreamResult(out);
		transformer.transform(source, result);	    
   		out.close();
		      
   		InputStreamReader inr = new InputStreamReader( getResponse() );

   		char[] charbuf = new char[2048];
		      
   		inr.read(charbuf,0,2048);
   		System.out.println( new String(charbuf) );
		      
   		inr.close();
   		
   		setMessage( "Transfer Complete" );
   		setProgress( 100 );
   		
   		//dispose();
   		}
   	catch ( Exception ex )
   		{
   		ex.printStackTrace();
   		}
   		
   	worker = null;
		}

	}
