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

/*************************************************************************
Name: POP.java

Input: 
3 parameters from a CGI form w/ the following names
user: username
pass: password
host: host to retrieve mail from

Functionality:
- Parses the input
- Log into POP server on the appropriate machine
- Find out how many emails the user has
- If the TOP command is supported on the POP server, retrieve the Subject,
  From, To, and Date info for each email
- Log out from the server

Output:
An HTML page that includes a link for each email (calls RetrieveMail.java), 
and the option to delete each email (calls Update.java).

Error Checks:
- Missing/incorrect username, password, or host.
- POP server not responding.
**************************************************************************/

public class POP extends HttpServlet{

/* Warn the CGI Form author that the POST method is preferred so that 
 * the user password is not being displayed on the URL line 
 */
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException{
	res.setContentType("text/html");
	ServletOutputStream out=res.getOutputStream();
	out.println("<HTML><HEAD><TITLE>Please use POST method</TITLE></HEAD>");
	out.println("<BODY><H4>Please use POST method for your CGI form for SECURITY reasons</H4></BODY></HTML>");
    }

/* The doPost class will handle the request */
    public void doPost(HttpServletRequest req, HttpServletResponse res) 
    throws ServletException, IOException{
	res.setContentType("text/html");
	ServletOutputStream out=res.getOutputStream();
	
	try{
	    // ======= Get the parameters from the CGI form =======
	    String user=req.getParameter("user");
	    String pass=req.getParameter("pass");
	    String host=req.getParameter("host");
	    if (user.equals("")){
		throw new ServletException("Missing Username");
	    }
	    if (pass.equals("")){
		throw new ServletException("Missing Password");
            }
	    if (host.equals("")){
                throw new ServletException("Missing Hostname");
            }

	    // ===== Create socket and log into POP3 =====
	    Socket sock=new Socket(host, 110);
            PrintStream in_sock=new PrintStream(sock.getOutputStream());
            DataInputStream out_sock=new DataInputStream(sock.getInputStream());
 
	    String pop_res;
            pop_res=out_sock.readLine();
            if (! pop_res.startsWith("+OK")){
                throw new ServletException("POP3 Server Not Ready");
            }

            in_sock.println("USER "+user);
	    pop_res=out_sock.readLine();
            if (! pop_res.startsWith("+OK")){
                throw new ServletException("Incorrect Username");
	    }		

            in_sock.println("PASS "+pass);
            pop_res=out_sock.readLine();
            if (! pop_res.startsWith("+OK")){ 
                throw new ServletException("Incorrect Password");
            }

	    // ======== Figure out how many emails ===========
	    StringTokenizer num_msg=new StringTokenizer(pop_res, " ");
	    num_msg.nextToken();  //+OK
	    num_msg.nextToken();  //username 
	    num_msg.nextToken();  //has
            int msg=Integer.parseInt(num_msg.nextToken());  //number of msgs

	    // ===== Retrive msgs into files if nummsg!=0 =====
	    if (msg == 0){
		out.println("<HTML><HEAD>");
		out.println("<TITLE>Email for "+user+" on "+host+"</TITLE></HEAD>");
		out.println("<BODY><H1>Email for "+user+" on "+host+"</H1>");
		out.println("You have 0 new mails!</BODY></HTML>");
	    }
	    else{
		// HTML tags
		out.println("<HTML><HEAD>");
                out.println("<TITLE>Email for "+user+" on "+host+"</TITLE></HEAD>");
                out.println("<BODY><H1>Email for "+user+" on "+host+"</H1>");
                out.println("You have "+msg+" new mail(s)!<HR>");
		out.println("<FORM ACTION=\"http://128.96.164.196:8080/servlet/group2.shenyang.Update\" METHOD=\"GET\">");

		// Set Cookies + other info
                out.println("<INPUT TYPE=\"hidden\" NAME=\"msg\" VALUE=\""+msg+"\">");
		Cookie userCookie=new Cookie("username", user);
		Cookie passCookie=new Cookie("password", pass);
		Cookie hostCookie=new Cookie("hostname", host);
		res.addCookie(userCookie);
		res.addCookie(passCookie);
		res.addCookie(hostCookie);

		// Output the HTML form 
		out.println("<UL>");
		String tmp;
		for (int i=1; i<=msg; i++){
		    out.println("<LI><A HREF=\"http://128.96.164.196:8080/servlet/group2.shenyang.RetrieveMail?mail="+i+"\">Email "+i+"</A>");
		    out.println("<INPUT TYPE=\"checkbox\" NAME=\"del"+i+"\">Delete this mail");
		    out.println("<UL>");

		    // Output the Subject lines if TOP command implemented
		    in_sock.println("TOP "+i+" 0");
		    tmp=out_sock.readLine();
		    if (tmp.startsWith("+OK")){
			while(! tmp.equals(".")){
			    tmp=out_sock.readLine();
			    if (tmp.startsWith("Date:") || tmp.startsWith("From:") || tmp.startsWith("To:") || tmp.startsWith("Subject:")){
				out.println("<LI>"+tmp);
			    }
			}
			out.println("</UL>");		
		    }		    
		}
		out.println("</UL>");
		out.println("<INPUT TYPE=\"submit\" VALUE=\"Update\">");
		out.println("</FORM></BODY></HTML>");
	    }		
            in_sock.println("QUIT");
	}
	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><H1>"+e+"</H1>");
	    out.println("The hostname you supplied is unknown, try again!");
	    out.println("</BODY></HTML>");
	}
	catch (IOException e){
	    out.println("<HTML><HEAD><TITLE>IOException</TITLE></HEAD>");
            out.println("<BODY><H1>"+e+"</H1>");
	    out.println("</BODY></HTML>");
	}
    }
}
	 
