package splppp0001;

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

import sun.net.smtp.SmtpClient;

public class Registration extends HttpServlet {

  static final String FROM = "Registration-SpLPPP@educ.di.unito.it";
  static final String TO = "baldoni@di.unito.it";

  int counter; 

  public void service(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {

      res.setContentType("text/html");
      PrintWriter out = res.getWriter();

      HTMLPage page = new HTMLPage();
      page.header.setTitle("Registrazione Laboratorio di SpLPPP");
      page.header.setAuthor("Matteo Baldoni");

      String cognome1 = req.getParameter("cognome1").trim();
      String nome1    = req.getParameter("nome1").trim();
      String email1   = req.getParameter("email1").trim();
      
      String cognome2 = req.getParameter("cognome2").trim();
      String nome2    = req.getParameter("nome2").trim();
      String email2   = req.getParameter("email2").trim();
      
      String commenti = req.getParameter("commenti").trim();

      if(cognome1.equals("") || nome1.equals("") || email1.equals("")) {
          page.body.addHeading(3,"Errore: dati mancanti");
          page.body.addParagraph("Il primo componente del gruppo " + 
                                 "deve sempre essere specificato in " +
                                 "tutti i suoi dati.");
      }
      else if(!(cognome2.equals("") && nome2.equals("") && email2.equals("")) &&
         (cognome2.equals("") || nome2.equals("") || email2.equals(""))) {
          page.body.addHeading(3,"Errore: dati mancanti");
          page.body.addParagraph("Mancano dei dati del secondo componente del " +
                                 "gruppo, deve sempre specificato in " +
                                 "tutti i suoi dati.");
      } else if (!containsAt(email1)) {
          page.body.addHeading(3,"Errore: nessun indirizzo di e-mail specificato.");
          page.body.addParagraph("L'indirizzo di e-mail: " + email1 +
                                 " specificato non e` accettabile. ");
      }
      else if ((!email2.equals("")) && (!containsAt(email2))) {
          page.body.addHeading(3,"Errore: nessun indirizzo di e-mail specificato.");
          page.body.addParagraph("L'indirizzo di e-mail: " + email2 +
                                 " specificato non e` accettabile. ");
      } 
      else {      
          page.body.addHeading(3,"Iscrizione effettuata");
          page.body.addParagraph("Gentile Sig. " + cognome1 +  
                                 ",<br><br>ricevera` una email di conferma dell'iscrizione all'inidirizzo " +
                                 "da lei specificato nel form, contenente il numero di gruppo assegnatole, " +
                                 "entro pochi minuti." +
                                 "<BR><BR>Grazie." );

          String message; 
          message = "Componente 1\n";
          message += "Cognome: " + cognome1 + "\n";
          message += "Nome: " + nome1 + "\n";
          message += "Email: " + email1 + "\n\n";

          if (!cognome2.equals("")) {
              message += "Componente 2\n";
              message += "Cognome: " + cognome2 + "\n";
              message += "Nome: " + nome2 + "\n";
              message += "Email: " + email2 + "\n\n";
          }

          if (!commenti.equals("")) {
              message += "Commenti:\n" + commenti + "\n";
          }
          
          int localCounter;
          synchronized(this) {
              localCounter = counter++;
              saveState();
          }
          
          message = "Iscrizione Gruppo: " 
                    + localCounter + ".\n"
                    + "Iscrizione effettuata da: " + req.getRemoteUser() + ".\n" 
                    + "Address: " + req.getRemoteAddr() + ".\n\n" 
                    + message;
          
          try {
              this.sendMail(TO, FROM, message, req); 
              this.sendMail(email1, TO, message, req); 
              if (!email2.equals("")) {
                  this.sendMail(email2, TO, message, req); 
              }
          }
          catch(IOException e) {
              page.body.addHeading(3,"Errore durante la sottomissione");
              page.body.addParagraph("Avvisare <A HREF=\"mailto:baldoni@di.unito.it\">Matteo Baldoni</A>.");
              page.body.addParagraph(e.toString());          }
      }

      out.println(page);                                                     

  }

  public void init(ServletConfig config) throws ServletException {
      super.init(config);
      try {
          FileReader fileReader = new FileReader("/www/sweb/servlets/splppp0001/InitDestroyCounter.initial");
          BufferedReader bufferedReader = new BufferedReader(fileReader);
          String initial = bufferedReader.readLine();
          counter = Integer.parseInt(initial);
          return;
      }
      catch(FileNotFoundException ignored) { }
      catch(IOException ignored) { }
      catch(NumberFormatException ignored) { }
    
      counter = 1;
  }

  public void saveState() {
      try {
          FileWriter fileWriter = new FileWriter("/www/sweb/servlets/splppp0001/InitDestroyCounter.initial");
          String initial = Integer.toString(counter);
          fileWriter.write(initial, 0, initial.length());
          fileWriter.close();
          return;
      }
      catch(IOException ignored) { 
          System.out.println("Non posso salvare");
      }
   }

   public void destroy() {
      saveState();
   }

   private void sendMail(String to, String from, String message, HttpServletRequest req) 
           throws IOException {
      try {
          SmtpClient smtp = new SmtpClient("speedy.educ.di.unito.it");  // assume localhost
          smtp.from(from);
          smtp.to(to);
     
          PrintStream msg = smtp.startMessage();

          msg.println("To: " + to);  // so mailers will display the To: address
          msg.println("Subject: Registrazione Laboratorio di SpLPPP");
          msg.println();
          msg.println(message);
          msg.println();
          msg.println("---");
          msg.println("Sent by " + HttpUtils.getRequestURL(req));

          smtp.closeServer();
      }
      catch (IOException e) {
          throw e;
      }

   }     

   private boolean containsAt(String address) {
        int i;
        for(i=0; i<address.length(); i++)
            if((address.substring(i,i+1)).equals("@")) break;
        if (i < address.length())
            return true;
        else
            return false;                       
   }

}
