package imap;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Using the IMAP protocol
// This servlet will take in the current mailbox, email, and
// tomailbox parameter... copy the current email to the chosen
// mailbox, and bring you back to email viewing mode
public class ImapCopyBox extends HttpServlet {

  // Defining resulting object out from request req and response res
  public void doGet(HttpServletRequest req, HttpServletResponse res)
  throws ServletException, IOException {

    res.setContentType("text/html");
    ServletOutputStream out=res.getOutputStream();

    try {

      // Retrieve login information from preset cookie
      Cookie[] cookie=new Cookie[3];
      String[] login=new String[3];
      cookie=req.getCookies();

      String username="0", password="0", hostname="0";

      for(int i=0; i<=2; i++) {
	login[i]=cookie[i].getName();
	if (login[i].equals("username")) 
	  username=cookie[i].getValue();
	else if (login[i].equals("password"))
	  password=cookie[i].getValue();
	else if (login[i].equals("hostname"))
	  hostname=cookie[i].getValue();
      }

 	// Retrieve parameter information
      String email=req.getParameter("email");
      String mailbox=req.getParameter("mailbox");
	String tomailbox=req.getParameter("tomailbox");

      // Creating a socket to the desired hostname's IMAP port
      Socket socket=new Socket(hostname, 143);
      PrintStream write_socket=new PrintStream(socket.getOutputStream());
      DataInputStream read_socket=new DataInputStream(socket.getInputStream());

      // Make sure target IMAP port is ready
      String imap_res=read_socket.readLine();
      if (! imap_res.startsWith("* OK")) 
	throw new ServletException("IMAP Server was not reachable this time");

      int command=1;

      // Make sure a correct username and/or password is provided
      write_socket.println(command+" login "+username+" "+password);
      imap_res=read_socket.readLine();
      if (! imap_res.startsWith(command+" OK")) 
	throw new ServletException("Invalid Username and/or Password");

	// Select inbox
      command++;
      write_socket.println(command+" select "+mailbox);
	imap_res=read_socket.readLine();
	if (imap_res.startsWith(command+" BAD") || imap_res.startsWith(command+" NO") ) 
		throw new ServletException("Invalid Mailbox");
	while (! imap_res.startsWith(command+" OK"))
		imap_res=read_socket.readLine();

      command++;
	write_socket.println(command+" copy "+email+" "+tomailbox);
	imap_res=read_socket.readLine();
	if (imap_res.startsWith(command+" BAD") || imap_res.startsWith(command+" NO") ) 
		throw new ServletException("Invalid ToMailbox"+email+" "+mailbox+" "+tomailbox);
	while (! imap_res.startsWith(command+" OK"))
		imap_res=read_socket.readLine();     
	
	command++;
      // Retrieve the headers for all the messages and print out to html page
      write_socket.println(command+" fetch "+email+" (body[header.fields (from date subject)] body[text])");
      read_socket.readLine();
      imap_res=read_socket.readLine();

	if (imap_res.startsWith(command+" BAD") || imap_res.startsWith(command+" NO") )
		throw new ServletException("Invalid Email message");
    
	out.println("<HTML><HEAD><TITLE>Email #"+email+" from mailbox:"+mailbox+"</TITLE></HEAD>");
      out.println("<BODY><H1>Email #"+email+" from mailbox:"+mailbox+"</H1><HR>");
	out.println("This message was copied over to Mailbox:"+tomailbox+"<HR>");

     	while (! imap_res.startsWith(command+" OK")) {
		if (imap_res.startsWith(" BODY"))
	  		out.println("<HR>");
		else if (imap_res.equals(")"))
	  		out.println("<HR>");
		else
	  		out.println(imap_res+"<BR>");

		imap_res=read_socket.readLine();
      }

      out.println("<FORM ACTION=\"http://128.96.164.196:8080/servlet/imap.ImapCopyBox\" METHOD=\"GET\">Copy message to Mailbox:<INPUT TYPE=\"text\" NAME=\"tomailbox\" SIZE=40>");
	out.println("<INPUT TYPE=\"hidden\" NAME=\"mailbox\" VALUE=\""+mailbox+"\">");
	out.println("<INPUT TYPE=\"hidden\" NAME=\"email\" VALUE=\""+email+"\">");
      out.println("<INPUT TYPE=\"submit\" VALUE=\"Copy\">");
    	out.println("</FORM></BODY></HTML>");

      out.println("<FORM ACTION=\"http://128.96.164.196:8080/servlet/imap.ImapView\" METHOD=\"GET\">");
	out.println("<INPUT TYPE=\"hidden\" NAME=\"mailbox\" VALUE=\""+mailbox+"\">");
      out.println("<INPUT TYPE=\"submit\" VALUE=\"Click here to go back to mailbox\">");
      out.println("</FORM></BODY></HTML>");

      command++;
      write_socket.println(command+" logout");
    }

    catch (ServletException e) {
      out.println("<HTML><HEAD><TITLE>"+e+"</TITLE></HEAD>");
      out.println("<BODY>"+e+"</BODY></HTML>");
    }

    catch (UnknownHostException e) {
      out.println("<HTML><HEAD><TITLE>Unknown Host</TITLE></HEAD>");
      out.println("<BODY>"+e);
      out.println("The hostname supplied is not recognized, try a different hostname.");
      out.println("</BODY></HTML>");
    }

    catch (IOException e) {
      out.println("<HTML><HEAD><TITLE>IOException</TITLE></HEAD>");
      out.println("<BODY>"+e);
      out.println("</BODY></HTML>");
    }
  }
}
