import	java.io.*;
import	java.net.*;
import  java.applet.*;

class MailSender extends Thread {
  private Socket s;
  private DataInputStream dis;
  private PrintStream ps;
  private String to, from, subject, date, message;
  private Thread session;
  private Applet ap;
    

  public static final	int port = 25;
  public static final String host = "www.georgetown.edu";
	

    public MailSender(String headers[], String newmessage, Applet a) {
		this.to 	= "mahe@cs.georgetown.edu";
		this.from 	= headers[0];
		this.subject 	= "Pizza Delivery";
		this.date 	= headers[1];
		this.message 	= newmessage;
		this.ap         = a;
	
    }

    public void run() {
      boolean SendError  = false;
        try {
            s = new Socket(host,port);
            dis = new DataInputStream(s.getInputStream());
            reply("220");

            ps = new PrintStream(s.getOutputStream());

            ps.println("HELO " + InetAddress.getLocalHost().getHostName());
            ps.flush();
            reply("250"); 

            ps.println("MAIL FROM: <" + from + ">");
            ps.flush();
            reply("250");

            ps.println("RCPT TO: <" + to + ">");
            ps.flush();
            reply("250");

            ps.println("DATA");
            ps.flush();
            reply("354");
	    ps.println("To:  "+to);
	    ps.println("From:  "+from);
	    ps.println("Date:  "+date);
	    ps.println("Subject:  "+subject);
			
            ps.println(message);

            ps.println(".");
            ps.flush();
	    reply("250");
	    ps.println("QUIT");
	    ps.flush();
	    reply("221");
        } catch(IOException e) {
        	System.out.println("MailSender: An error has occured while communicating with the SMTP server.");
        	System.out.println(e.toString());
		SendError = true;
        } finally {
        	try {
		  if (SendError)
		    ap.showStatus ("Error in sending your order, Try Again Later");
		  else
		    ap.showStatus ("Your Order has been Sent!");
   				s.close();
   			} catch (IOException e) {
   			} catch (NullPointerException e) {
   			}
        }
     }
    
    public void start() {
		if (session == null) {
			session = new Thread(this);
			session.start();
		}
	}
    
   private void reply(String expected) throws IOException {
    	String reply = dis.readLine();
    	
    	if (reply.startsWith(expected) == false) {
   		throw new IOException ("Unknown response from SMTP server.");
     	}
    	
    }

}