/* Java Servlet example - Netprog Pizza Server
   Uses an HTTP Cookie
*/

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class PizzaCookie extends HttpServlet {
    HttpServletRequest request;
    HttpServletResponse response;
    PrintWriter out;

    static String path="c:\\jdk1.3\\tomcat\\webapps\\Root\\PizzaCookie\\";

    // we only either GET or POST requests
    public void doPost(HttpServletRequest rq,
		      HttpServletResponse resp)
	throws IOException, ServletException {

	doGet(rq,resp);
    }

    public void doGet(HttpServletRequest rq,
		      HttpServletResponse resp)
	throws IOException, ServletException {

	request = rq;
	response = resp;

	// tell the browser we are sending back HTML
	response.setContentType("text/html");

	// grab a writer back to the browser
	out = response.getWriter();

	// now go handle this request
	HandleRequest();
    }


    // Inside HandleRequest we grab exceptions and deal with them
    // If we just thow them upward - we end up sending the Java
    // call stack to the browser (probably not a good idea!)

    void HandleRequest() throws IOException {
	try {

	    // send back our logo (always)
	    SendFile(path+"logo.html");

	    // First - find out what kind of a request this is.
	    // Each form has a hidden field named formname that
	    // tells us which form the request comes from.
	    // Possible values:
	    //    nothing - send back login screen
	    //    "login" - this is a login attempt
	    //    "order" - this is a pizza order

	    String form = request.getParameter("formname");

	    // If there is no field named "formname" we should
	    // check for a cookie named "pizzacookie"
	    // If we get this cookie - use it as the user name
	    if (form==null) {
		// First attempt a cookie based automatic login
		if (! CookieLogin()) {
		    // no valid cookie - send login form
		    SendFile(path+"loginform.html");
		}
	    } else if (form.equals("login")) {
		// this is a login attempt
		Login();
	    } else if (form.equals("order")) {
		// this is a pizza order
		Order();
	    } else {
		// who knows?
		SendFile(path+"badrequest");
	    }
	} catch (Exception e) {
	    // Any exception is handled by punting...
	    SendFile(path+"error");
	}
    }

    // Order() handles orders for pizza. 
    // 

    void Order() throws IOException {
	// Order request - we expect to get a cookie named "pizzacookie"
	// Check before worrying about the pizza and size

	String name=getNameCookie();

	// Validate is based on name only
	// we got the password earlier
	// In "real life" this needs to be more robust, perhaps
	// using a session key
	if (ValidateName(name)) {
	    String pizza = request.getParameter("pizza");
	    String size = request.getParameter("size");

	    // First make sure we got a complete order
	    if (ValidateOrder(pizza,size)) {
		// Everything looks good - print a receipt
		Receipt(name,pizza,size);
	    } else {
		// Bad order
		SendFile(path+"nicetry.html");
	    }
	} else {
	    // Invalid login - flame the loser
	    SendFile(path+"baduser.html");
	    SendFile(path+"loginform.html");
	}
    }


    // Login() takes care of login requests. If everything is OK
    // (valid name and password) we send back an order form with
    // and set a cookie.

    void Login() throws IOException {

	// Login request - we expect "name" and "password"
	String name = request.getParameter("name");
	String pass = request.getParameter("password");

	if (ValidateUser(name,pass)) {
	    // Valid login - set cookie to indicate user name
	    response.addCookie(new Cookie("javapizza",name));

	    // Send back message and the order form
	    out.println("<H2 ALIGN=CENTER>Hello ");
	    out.println("<FONT COLOR=BLUE>"+name+"</FONT>, place your order</H2>");
	    SendFile(path+"orderform.html");
	} else {
	    // Invalid login - flame the loser
	    SendFile(path+"baduser.html");
	    SendFile(path+"loginform.html");
	}
    }


    // CookieLogin() takes care of a returning visitor

    boolean CookieLogin() throws IOException {
	String name = getNameCookie();

	if (ValidateName(name)) {
	    // Send back message and the order form
	    out.println("<H2 ALIGN=CENTER>Hello ");
	    out.println("<FONT COLOR=BLUE>"+name+"</FONT>, place your order</H2>");
	    SendFile(path+"orderform.html");
	    return(true);
	} else {
	    // no valid cookie - return false
	    return(false);
	}
    }


    // Receipt() sends an HTML receipt back to the browser
    // Should probably use the Calendar class instead of
    // Date here...


    void Receipt(String name, String pizza, String size) throws IOException {

	Date d = new Date();

	// create a string that holds current date
	SimpleDateFormat f = new SimpleDateFormat("EEEE, MMMM d, yyyy");
	String ds = f.format(d);

	// create a string that holds current time
	SimpleDateFormat f1 = new SimpleDateFormat("hh:mm a");
	String ts = f1.format(d);

	// pizza will be ready in 45 minutes:
	Date dout = new Date(d.getTime()+1000*60*45);

	String ts1 = f1.format(dout);
	
	// create a string that holds time pizza is ready

	out.println("<H2 ALIGN=CENTER>Thanks for your order ");
	out.println(name+"</H2>");

	out.println("<TABLE BORDER=0><TR>\n");
	out.println("<TR><TH COLSPAN=2 ALIGN=CENTER>RECEIPT</TH></TR>");
	out.println("<TR><TH ALIGN=RIGHT>Name:</TH><TD>"+name+"</TD></TR>");
	
	out.println("<TR><TH ALIGN=RIGHT>Date:</TH>");
	out.println("<TD>"+ds+"</TD></TR>");

	out.println("<TR><TH ALIGN=RIGHT>Time:</TH>");
	out.println("<TD>"+ts+"</TD></TR>");

	out.println("<TR><TH ALIGN=RIGHT>Pizza:</TH>");
	out.println("<TD>"+pizza+"</TD></TR>");

	out.println("<TR><TH ALIGN=RIGHT>Size:</TH>");
	out.println("<TD>"+size+"</TD></TR>");

	out.println("<TH>Time Ready:</TH>");
	out.println("<TD>"+ts1+"</TD></TR>");
	out.println("<TR><TH ALIGN=RIGHT>Amount Due:</TH>");
	if (size.equals("small"))
	    out.println("<TD>$6.50</TD></TR>");
	else if (size.equals("medium"))
	    out.println("<TD>$8.50</TD></TR>");
	else
	    out.println("<TD>$10.50</TD></TR>");
	out.println("</TABLE>\n");
    }


    // Send the named file to the browser
    void SendFile(String filename) throws IOException,FileNotFoundException  {
	BufferedReader f = new BufferedReader(new FileReader(filename));
	String line;
      
	while ((line=f.readLine())!=null) {
	    out.println(line);
	}
	f.close();
    }

    // Method that checks the rinky-dink password file for 
    // the name/password we got

    boolean ValidateUser(String name,String pass) throws IOException {
	BufferedReader f = new BufferedReader(new FileReader(path+"pw"));
	String n,p;

	while ((n=f.readLine())!=null) {
	    if ((p=f.readLine())!=null) {
		if ((n.equals(name))&&(p.equals(pass))) {
		    f.close();
		    return(true);
		} 
	    } else {
		f.close();
		return(false);
	    }
	}
	f.close();
	return(false);
    }

    boolean ValidateName(String name) throws IOException {
	BufferedReader f = new BufferedReader(new FileReader(path+"pw"));
	String n,p;

	while ((n=f.readLine())!=null) {
	    if ((p=f.readLine())!=null) {
		if (n.equals(name)) {
		    f.close();
		    return(true);
		} 
	    } else {
		f.close();
		return(false);
	    }
	}
	f.close();
	return(false);
    }


    // Method that checks to make sure the pizza order is valid.
    // Here we just have hard-coded constants...
    // (would be nice to read valid pizza names/sizes from a file)

    boolean ValidateOrder(String pizza,String size) throws IOException {

	if ((pizza==null)||(size==null)) {
	    return(false);
	}

	if (pizza.equals("Cheese") ||
	    pizza.equals("Veggie") ||
	    pizza.equals("Pepperoni") ||
	    pizza.equals("Sausage")) {
	    // so far so good - check the size
	    if (size.equals("large") ||
		size.equals("medium") ||
		size.equals("small")) {
		// good order - this is a grat customer!
		return(true);
	    }
	}
	// wise-guy - invalid order
	return(false);
    }

    String getNameCookie() {
	String name=null;
	Cookie c[] = request.getCookies();
	// search for the cookie named "javapizza"
	for (int i=0;i<c.length;i++) {
	    if (c[i].getName().equals("javapizza")) {
		name = c[i].getValue();
		break;
	    }
	}
	return(name);
    }

}




