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, and email parameter
// and set the delete flag on that message.  It will then return
// you to current mailbox view mode.
public class ImapDel 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");

      // 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");

      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+" store "+email+" +flags (\\deleted)");

      command++;
      String emails="0";

      // Find out how much mail the user has
      write_socket.println(command+" select "+mailbox);
      imap_res=read_socket.readLine();
      while (! imap_res.startsWith(command+" OK")) {
	StringTokenizer breakline=new StringTokenizer(imap_res, " ");
	breakline.nextToken();
	String secondword=breakline.nextToken();
	String thirdword=breakline.nextToken();
	if (thirdword.equals("EXISTS")) 
	  emails=secondword;
	imap_res=read_socket.readLine();
      }

      out.println("<HTML><HEAD>");
      out.println("<TITLE>Email for "+username+" on "+hostname+" in mailbox:"+mailbox+"</TITLE></HEAD>");
      out.println("<BODY><H1>Email for "+username+" on "+hostname+" in mailbox:"+mailbox+"</H1>");
      out.println("<BR>Email #"+email+" has been set for deletion.<HR>");

      if (emails.equals("0")) 
		out.println("You have no mail.<HR>");

	else {
		out.println("You have "+emails+" mail message(s).<HR>");

      	command++;

      	// Retrieve the headers for all the messages and print out to html page
      	write_socket.println(command+" fetch 1:"+emails+" (body[header.fields (from date subject)])");
      	imap_res=read_socket.readLine();
      	while (! imap_res.startsWith(command+" OK")) {
			if (imap_res.startsWith("*")) {
	  			StringTokenizer breakline=new StringTokenizer(imap_res, " ");
	  			breakline.nextToken();
          			String msgnum=breakline.nextToken();
	  			out.println("<LI><A HREF=\"http://128.96.164.196:8080/servlet/imap.ImapRead?mailbox="+mailbox+"&email="+msgnum+"\"><B>EMAIL #"+msgnum+"</B></A>");
	  			out.println("<A HREF=\"http://128.96.164.196:8080/servlet/imap.ImapDel?mailbox="+mailbox+"&email="+msgnum+"\"> delete</A>");
	  			out.println("</UL>");
	  			for(int header=1; header<=3; header++) {
	    				imap_res=read_socket.readLine();
	    				out.println("<LI>"+imap_res+"</UL>");
	  			}
			}
		out.println("<HR>");
		imap_res=read_socket.readLine();
      	}
	}

      out.println("<FORM ACTION=\"http://128.96.164.196:8080/servlet/imap.ImapListBox\" METHOD=\"GET\">");
      out.println("<INPUT TYPE=\"submit\" VALUE=\"Click here to select or create a new mailbox\">");
      out.println("</FORM>");

      out.println("<FORM ACTION=\"http://128.96.164.196:8080/servlet/imap.ImapClean\" METHOD=\"GET\">");
	out.println("<INPUT TYPE=\"hidden\" NAME=\"mailbox\" VALUE=\""+mailbox+"\">");
      out.println("<INPUT TYPE=\"submit\" VALUE=\"Click here to update this 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>");
    }
  }
}
