package com.silverwrist.util.test;

import java.io.*;
import java.util.*;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.*;

public class TestMultiHandler
{
  private MimeMultipart multipart;
  private int count;
  private Vector params;

  static class ServletDataSource implements DataSource
  {
    private ServletRequest request;
    private InputStream istm = null;

    public ServletDataSource(ServletRequest request)
    {
      this.request = request;

    } // end constructor

    public InputStream getInputStream() throws IOException
    {
      if (istm==null)
	istm = request.getInputStream();
      return istm;

    } // end getInputStream

    public OutputStream getOutputStream() throws IOException
    {
      throw new IOException("tried to get OutputStream on servlet input?!?!?");

    } // end getOutputStream

    public String getContentType()
    {
      return request.getContentType();

    } // end getContentType

    public String getName()
    {
      return "servlet";

    } // end getName

  } // end class ServletDataSource

  public TestMultiHandler(ServletRequest request) throws IOException
  {
    if (!canHandle(request))
      throw new UnsupportedOperationException("data type doesn't match");

    try
    { // OK, this is the tricky part...
      ServletDataSource ds = new ServletDataSource(request);
      multipart = new MimeMultipart(ds);
      count = multipart.getCount();
      params = new Vector(count);
      // OK, that's enough for now
      
    } // end try
    catch (MessagingException e)
    { // better run like hell, 'cos this may not work
      throw new IOException("Got MessagingException: " + e.getMessage());

    } // end catch

  } // end constructor

  public static boolean canHandle(ServletRequest request)
  {
    String ctype = request.getContentType();
    return (ctype.startsWith("multipart/form-data"));

  } // end canHandle

  public int getCount()
  {
    return count;

  } // end getCount

  public void dump(PrintWriter out)
  {
    try
    { // print out all parts
      int ct = multipart.getCount();
      out.println("Number of parts: " + String.valueOf(ct));

      for (int i=0; i<ct; i++)
      { // loop through all the parts
	out.println("--- PART " + String.valueOf(i) + " ---");
	MimeBodyPart part = (MimeBodyPart)(multipart.getBodyPart(i));
	out.println("got it");
	String foo = part.getContentType();
	out.println("Content type: " + foo);
	foo = part.getDisposition();
	out.println("Content disposition: " + foo);
	String[] disphdr = part.getHeader("Content-Disposition");
	for (int j=0; j<disphdr.length; j++)
	  out.println("Content-Disposition header[" + String.valueOf(j) + "]: " + disphdr[j]);

      } // end for

    } // end try
    catch (MessagingException e)
    { // whoops!
      out.println("THREW MessagingException: " + e.getMessage());

    } // end catch

  } // end dump

} // end class TestMultiHandler
