import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
import java.io.*;

public class MailboxDialog extends Frame implements ActionListener {

  public MailboxDialog(ClientSocket clientsocket)
  {
   
    setSize(400,400);
    cs = clientsocket;
    getNewMessages();
  }
  
  public void getNewMessages()
  {
    Label msglabel;
    String command,buf,messageCode;
    messageArray = new String[50];
    messageCounter = 0;

    command = "GETNEWMESSAGES";
    try
      {
	cs.Write(command);
	buf = cs.Read();
	System.out.println("response " + buf);
      }
    catch(IOException io)
      {
	System.out.println("IO error");
	return;
      }

    StringTokenizer tokenizer = new StringTokenizer(buf,",");
    messageCode = tokenizer.nextToken();
   

    while(messageCode.equals("162"))
      {
		    
	if(messageCounter>=50)
	  break;
	
	messageArray[messageCounter]=buf;
	messageCounter++;
	  
	try
	  {
	    cs.Write(command);
	    buf = cs.Read();
	    System.out.println("response " + buf);
	  }
	catch(IOException io)
	  {
	    System.out.println("IO error");
	    return;
	  }
	messageCode = tokenizer.nextToken();
      }

    if (messageCounter==0)
      {
	this.setLayout(null);
	if (messageCode.equals("161"))
	    msglabel = new Label("No New Messages");
 	else 
	    msglabel = new Label("Error in retrieving mail");

	add(msglabel);
	msglabel.setBounds(175,200,50,50);
      }
    else
      {
	setLayout(new GridLayout((messageCounter+1),1));
	
	for(int i=0; i<messageCounter;i++)
	  {
	    add(new MessageTextArea( (messageArray[i]),cs )) ;
	  }
      }
    Panel notpanel = new Panel();
    add(notpanel);
    notpanel.setLayout(null);
    
    Label notiflabel = new Label("Notifications:");
    notpanel.add(notiflabel);
    notiflabel.setBounds(30,130,100,20);
    
    Label clicklabel = new Label("Click to respond");
    notpanel.add(clicklabel);
    clicklabel.setBounds(225,130,130,20);

    Button cancelbutton = new Button("Cancel");
    cancelbutton.setBounds(160,130,60,30);
    notpanel.add(cancelbutton);
    cancelbutton.addActionListener(this);
  }
  

  public void actionPerformed(ActionEvent evt)
  {
    String arg = evt.getActionCommand();
    if (arg.equals("cancel"))
      setVisible(false);
    dispose();
    validate();
  }
    private String[] messageArray; 
    private int messageCounter;
    private ClientSocket cs;
}



