package net;

import ip.gui.frames.ClosableFrame;

import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;


public class CheckMail extends Applet {

  private Socket socket;
  private String serverHostName = null;
  private PrintWriter ps;
  private InetAddress rina, lina;
  private int popPort = 110;
  private boolean standalone = false;

  private CheckMailPanel form;


  /**
   * Initialize the applet.
   */
  public void init() {
    form = new CheckMailPanel(this);
    add(form);
    form.setSize(300, 300);
    setBackground(Color.blue);
    if (serverHostName == null) serverHostName = getCodeBase().getHost();
    System.out.println("ServerHostName=" + serverHostName);
  }


  /**
   * Show status text to the user.
   */
  public void showStatus(String s) {

    System.out.println(s);
    if (standalone) return;
    super.showStatus(s);
  }

  private BufferedReader buf_reader;

  /**
   * Perform check for e-mail.
   */
  public void checkForMail() throws IOException, NumberFormatException, Exception {

    showStatus("Checking for mail on " + serverHostName);

    socket = new Socket(serverHostName, popPort);    //  open a connection
    String rs;

    try {
      rina = socket.getInetAddress();
      lina = rina.getLocalHost();

      //
      //  Conversion of the PrintStream due to deprication.
      //     ps = new PrintStream(socket.getOutputStream());
      //
      //  Print values and objects to a Writer.
      //
      ps = new PrintWriter(
          socket.getOutputStream());

      //
      //  Conversion of the DataInputStream due to deprecation.
      //    dis  = new DataInputStream(socket.getInputStream());
      //
      //  Use BufferedReader instead of DataInputStream.
      //
      buf_reader = new BufferedReader(
          new InputStreamReader(socket.getInputStream()));

      //
      //  Check for messages
      //
      sendline("USER " + form.getId());
      rs = sendline("PASS " + form.getPswd());
      //if (rs.charAt(0) != '+') throw new Exception("Incorrect password");
      rs = sendline("STAT");
    } catch (Exception ex) {
      socket.close();
      throw ex;
    }

    // Close connection
    socket.close();

    // Parse result
    int r = 0;
    r = Integer.parseInt(rs.substring(4, rs.indexOf(" messages")));

    // Update result field
    form.getResultField().setText(Integer.toString(r));
  }

  /**
   * Send a line of data to the server, and return the handshake.
   */
  String sendline(String data) throws IOException {

    System.out.println("sendline out:" + data);
    ps.println(data);
    ps.flush();

    //
    //  Conversion of the DataInputStream due to deprication.
    //
    // String s = dis.readLine();
    //
    String s = buf_reader.readLine();
    System.out.println("sendline in:" + s);
    return s;
  }


  /**
   * Main routine, for running as a standalone application.
   */
  public static void main(String args[]) {

    CheckMail ap = new CheckMail();
    ap.serverHostName = "mail.snet.ip.net";
    ap.standalone = true;

    ClosableFrame fr = new ClosableFrame("CheckMail");
    ap.init();
    fr.add("Center", ap);
    fr.setSize(300, 300);
    fr.setVisible(true);
    ap.start();
  }

  public Socket getSocket() {
    return socket;
  }

  public void setSocket(Socket socket) {
    this.socket = socket;
  }

  public String getServerHostName() {
    return serverHostName;
  }

  public void setServerHostName(String serverHostName) {
    this.serverHostName = serverHostName;
  }

  public PrintWriter getPs() {
    return ps;
  }

  public void setPs(PrintWriter ps) {
    this.ps = ps;
  }

  public InetAddress getRina() {
    return rina;
  }

  public void setRina(InetAddress rina) {
    this.rina = rina;
  }

  public InetAddress getLina() {
    return lina;
  }

  public void setLina(InetAddress lina) {
    this.lina = lina;
  }

  public int getPopPort() {
    return popPort;
  }

  public void setPopPort(int popPort) {
    this.popPort = popPort;
  }

  public boolean isStandalone() {
    return standalone;
  }

  public void setStandalone(boolean standalone) {
    this.standalone = standalone;
  }

  public CheckMailPanel getForm() {
    return form;
  }

  public void setForm(CheckMailPanel form) {
    this.form = form;
  }

  public BufferedReader getBuf_reader() {
    return buf_reader;
  }

  public void setBuf_reader(BufferedReader buf_reader) {
    this.buf_reader = buf_reader;
  }
}


/**
 * Form for obtaining e-mail user id and password from the user.
 */
class CheckMailPanel
    extends Panel implements ActionListener {

  private CheckMail applet;

  // The form's elements...
  private Label idLabel;
  private TextField idField;
  private Label pswdLabel;
  private TextField pswdField;
  private Button button;
  private Label resultLabel;
  private TextField resultField;

  /**
   * The constructor.
   */
  public CheckMailPanel(CheckMail ap) {

    applet = ap;
    setBackground(Color.blue);
    setLayout(new GridLayout(7, 1));

    // Instantiate all the elements, and add them to the form...
    add(button = new Button("Check For Mail"));
    button.addActionListener(this);
    add(idLabel = new Label("Id:"));
    add(idField = new TextField(20));
    add(pswdLabel = new Label("Password:"));
    add(pswdField = new TextField(20));
    pswdField.setEchoChar('*');
    add(resultLabel = new Label("Messages Waiting:"));
    add(resultField = new TextField(6));
    resultField.setEditable(false);

    // Set the size of the form
    setSize(250, 250);
  }


  /**
   * Return the value of the ID field in the form.
   */
  public String getId() {
    return idField.getText();
  }


  /**
   * Return the value of the password field in the form.
   */
  public String getPswd() {
    return pswdField.getText();
  }


  //
  //  Updated to the new Event model.
  //
  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == button) {

      try {
        applet.checkForMail();
      } catch (Exception ex) {
        applet.showStatus("Error; unable to check for messages:\n  " + ex.toString());
        return;
      }
      applet.showStatus("Completed.");
    }
  }

  public CheckMail getApplet() {
    return applet;
  }

  public void setApplet(CheckMail applet) {
    this.applet = applet;
  }

  public Label getIdLabel() {
    return idLabel;
  }

  public void setIdLabel(Label idLabel) {
    this.idLabel = idLabel;
  }

  public TextField getIdField() {
    return idField;
  }

  public void setIdField(TextField idField) {
    this.idField = idField;
  }

  public Label getPswdLabel() {
    return pswdLabel;
  }

  public void setPswdLabel(Label pswdLabel) {
    this.pswdLabel = pswdLabel;
  }

  public TextField getPswdField() {
    return pswdField;
  }

  public void setPswdField(TextField pswdField) {
    this.pswdField = pswdField;
  }

  public Button getButton() {
    return button;
  }

  public void setButton(Button button) {
    this.button = button;
  }

  public Label getResultLabel() {
    return resultLabel;
  }

  public void setResultLabel(Label resultLabel) {
    this.resultLabel = resultLabel;
  }

  public TextField getResultField() {
    return resultField;
  }

  public void setResultField(TextField resultField) {
    this.resultField = resultField;
  }
}