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


public class RequestServlet extends HttpServlet {
 
  public void init() {
    /*
     * On ne fait rien !
     */        
  }

  public void destroy() {
    /*
     * On ne fait rien !
     */
  }

  public void service(HttpServletRequest request, HttpServletResponse response)
	throws IOException {
    /*
     * On recupere la session creee par la servlet d'authentification pour ce
     * client.
     */
    HttpSession clientSession = request.getSession(false);
    /*
     * Si la requete du client ne se place pas dans le cadre d'une session, on
     * redirige ce dernier vers la phase d'authentification.
     */
    if (clientSession == null) {
      response.sendRedirect("http://zazie.enst.fr:8080/exo2.html");
      return;
    }
    /*
     * A partir de la session on recupere le numero de producteur, la
     * connection a la base de donnees, eventuellement son prenom et son nom.
     */
    Connection aConnection = null;
    String prenom = "";
    String nom = "";
    int pid = -1;
    Object objectHandle = clientSession.getAttribute("connection");
    if (objectHandle instanceof Connection) {
      aConnection = (Connection)objectHandle;
    } else {
      serviceError(response, nom, prenom, "Une erreur interne s'est produite");
      clientSession.invalidate();
      return;
    }
    objectHandle = clientSession.getAttribute("prod");
    if (objectHandle instanceof Integer) {
      pid = ((Integer)objectHandle).intValue();
    } else {
      serviceError(response, nom, prenom, "Une erreur interne s'est produite");
      try {
	aConnection.close();
      } catch (SQLException x) {}
      clientSession.invalidate();
      return;
    }
    objectHandle = clientSession.getAttribute("prenom");
    if (objectHandle instanceof String) 
      prenom = (String)objectHandle;
    objectHandle = clientSession.getAttribute("nom");
    if (objectHandle instanceof String) 
      nom = (String)objectHandle;
    /*
     * On s'assure que la connection a la base de donnees soit toujours
     * ouverte ...
     */
    try {
      if (aConnection.isClosed()) {
	serviceError(response, nom, prenom, "Une erreur interne s'est produite");
	clientSession.invalidate();
	return;
      }
    } catch (SQLException x) {
      serviceError(response,  nom, prenom, x.toString());
      clientSession.invalidate();
      try {
	aConnection.close();
      } catch (SQLException e) {}
      return;      
    }
    /*
     * On cree un statement SQL ...
     */
    Statement aStmt = null;
    try {
      aStmt = aConnection.createStatement();
    } catch (SQLException x) {
      serviceError(response,  nom, prenom, x.toString());
      clientSession.invalidate();
      try {
	aConnection.close();
      } catch (SQLException e) {}
      return;
    }
    /*
     * ... Pour executer une requete :
     * On veut connaitre les recoltes du producteur numero pid.
     */
    ResultSet aRSet = null;
    try {
      aRSet  = aStmt.executeQuery("select v.cru, v.mill, v.degre, r.qte from p, r, v where p.np = " + pid + " and p.np = r.np and r.nv = v.nv");
    } catch (SQLException x) {
      serviceError(response, nom, prenom, x.toString());
      clientSession.invalidate();
      try {
	aConnection.close();
      } catch (SQLException e) {}
      return;
    }
    /*
     * On cree une page HTML pour repondre a la requete du producteur.
     */
    response.setContentType("text/HTML");
    PrintWriter aHTMLPage = response.getWriter();
    aHTMLPage.println("<html>");
    aHTMLPage.println("  <head>");
    aHTMLPage.println("    <title>La page des producteurs de vins</title>");
    aHTMLPage.println("  </head>");
    aHTMLPage.println("  <body bgcolor=\"ivory\">");
    aHTMLPage.println("  <center>");
    /*
     * Si le resultat de la requete SQL est no rows selected ...
     * On retourne au producteur un message specifique.
     * Sinon on lui renvoie la liste des vins recoltes ...
     */
    try {
      if (!aRSet.next()) {
	if (nom.length() > 0 || prenom.length() > 0)
	  aHTMLPage.println("      <h1>" + prenom + " " + nom + "</h1>");
	aHTMLPage.println("      <h3>Vous n'avez réalisé aucune récolte ...</h3>");
	aHTMLPage.println("    </center>");
	aHTMLPage.println("  </body>");
	aHTMLPage.println("</html>");
	clientSession.invalidate();
	try {
	  aConnection.close();
	} catch (SQLException x) {}
	return;
      }      
    } catch (SQLException x) {
      serviceError(response, nom, prenom, x.toString());
      clientSession.invalidate();
      try {
	aConnection.close();
      } catch (SQLException e) {}
      return;
    }

    /*
     * On presente les donnees des recolte sous forme de tableau.
     */
    if (nom.length() > 0 || prenom.length() > 0)
      aHTMLPage.println("      <h1>" + prenom + " " + nom + "</h1>");
    aHTMLPage.println("      <h3>Les récoltes que vous avez effectuées sont les suivantes :</h3>");
    aHTMLPage.println("      <table border=\"0\" cellspacing=\"10\" cellpadding=\"0\">");
    aHTMLPage.println("        <tr>");
    aHTMLPage.println("          <td>");
    aHTMLPage.println("            <h4>cru</h4>");    
    aHTMLPage.println("          </td>");    
    aHTMLPage.println("          <td>");
    aHTMLPage.println("            <h4>millésime</h4>");    
    aHTMLPage.println("          </td>");    
    aHTMLPage.println("          <td>");
    aHTMLPage.println("            <h4>degré</h4>");    
    aHTMLPage.println("          </td>");    
    aHTMLPage.println("          <td>");
    aHTMLPage.println("            <h4>quantité</h4>");    
    aHTMLPage.println("          </td>");    
    aHTMLPage.println("        </tr>");

    try {	
      do {
	aHTMLPage.println("        <tr>");
	aHTMLPage.println("          <td>");
        aHTMLPage.println(aRSet.getString(1));
	aHTMLPage.println("          </td>");
	aHTMLPage.println("          <td>");
        aHTMLPage.println(aRSet.getInt(2));
	aHTMLPage.println("          </td>");
	aHTMLPage.println("          <td>");
        aHTMLPage.println(aRSet.getFloat(3));
	aHTMLPage.println("          </td>");
	aHTMLPage.println("          <td>");
        aHTMLPage.println(aRSet.getInt(4));
	aHTMLPage.println("          </td>");	
        aHTMLPage.println("        </tr>");
      } while (aRSet.next());
    } catch (SQLException x) {
      serviceError(response, nom, prenom, x.toString());
      clientSession.invalidate();
      try {
	aConnection.close();
      } catch (SQLException e) {}
      return;
    }
    aHTMLPage.println("      </table>");

    /*
     * On cree un autre statement SQL ...
     */
    try {
      aStmt.close();
      aStmt = aConnection.createStatement();
    } catch (SQLException x) {
      serviceError(response, nom, prenom, x.toString());
      clientSession.invalidate();
      try {
	aConnection.close();
      } catch (SQLException e) {}
      return;
    }

    /*
     * ... Pour executer une requete :
     * On veut connaitre les achats concernant les recoltes du producteur
     * numero pid.
     */
    aRSet = null;
    try {
      aRSet  = aStmt.executeQuery("select v.cru, v.mill, v.degre, a.qte, a.dat, b.nomb from p, r, v, a, b where p.np = " + pid + " and p.np = r.np and r.nv = v.nv and v.nv = a.nv and a.nb = b.nb");
    } catch (SQLException x) {
      serviceError(response, nom, prenom, x.toString());
      clientSession.invalidate();
      try {
	aConnection.close();
      } catch (SQLException e) {}
      return;
    }

    /*
     * Si le resultat de la requete SQL est no rows selected ...
     * On retourne au producteur un message specifique.
     * Sinon on lui renvoie la liste des achats concernant ses recoltes ...
     */
    try {
      if (!aRSet.next()) {
	aHTMLPage.println(    "<h3>Vous n'avez réalisé aucune vente sur vos récoltes ...</h3>");
      } else {
	aHTMLPage.println("      <h3>Les ventes réalisées sur vos récoltes sont les suivantes :</h3>");
	aHTMLPage.println("      <table border=\"0\" cellspacing=\"10\" cellpadding=\"0\">");
	aHTMLPage.println("        <tr>");
	aHTMLPage.println("          <td>");
	aHTMLPage.println("            <h4>cru</h4>");    
	aHTMLPage.println("          </td>");    
	aHTMLPage.println("          <td>");
	aHTMLPage.println("            <h4>millésime</h4>");    
	aHTMLPage.println("          </td>");    
	aHTMLPage.println("          <td>");
	aHTMLPage.println("            <h4>degré</h4>");    
	aHTMLPage.println("          </td>");    
	aHTMLPage.println("          <td>");
	aHTMLPage.println("            <h4>nom de l'acheteur</h4>");    
	aHTMLPage.println("          </td>");    
	aHTMLPage.println("          <td>");
	aHTMLPage.println("            <h4>date de la vente</h4>");    
	aHTMLPage.println("          </td>");    
	aHTMLPage.println("          <td>");
	aHTMLPage.println("            <h4>quantité vendue</h4>");    
	aHTMLPage.println("          </td>");    
	aHTMLPage.println("        </tr>");

	do {
	  aHTMLPage.println("        <tr>");
	  aHTMLPage.println("          <td>");
	  aHTMLPage.println(aRSet.getString(1));
	  aHTMLPage.println("          </td>");
	  aHTMLPage.println("          <td>");
	  aHTMLPage.println(aRSet.getInt(2));
	  aHTMLPage.println("          </td>");
	  aHTMLPage.println("          <td>");
	  aHTMLPage.println(aRSet.getFloat(3));
	  aHTMLPage.println("          </td>");
	  aHTMLPage.println("          <td>");
	  aHTMLPage.println(aRSet.getString(6));
	  aHTMLPage.println("          </td>");
	  aHTMLPage.println("          <td>");
	  aHTMLPage.println(aRSet.getDate(5).toString());
	  aHTMLPage.println("          </td>");
	  aHTMLPage.println("          <td>");
	  aHTMLPage.println(aRSet.getInt(4));
	  aHTMLPage.println("          </td>");
	  aHTMLPage.println("        </tr>");
	} while (aRSet.next());
      }
    } catch (SQLException x) {
      serviceError(response, nom, prenom, x.toString());
      clientSession.invalidate();
      try {
	aConnection.close();
      } catch (SQLException e) {}
      return;
    }
    aHTMLPage.println("      </table>");

    aHTMLPage.println("    </center>");    
    aHTMLPage.println("    <hr>");
    aHTMLPage.println("    <address><a href=\"mailto:nagat@enst.fr\">Mael Nagat</a></address>");
    aHTMLPage.println("  </body>");
    aHTMLPage.println("</html>");

    /*
     * On detruit la session de ce client et la connection a la BD.
     */
    clientSession.invalidate();
    try {
      aConnection.close();
    } catch (SQLException x) {}

  }

  private void serviceError(HttpServletResponse response,
				 String nomClient, String prenomClient, String message)
	throws IOException {
    /*
     * Il se peut que l'on ait commence de construire une reponse.
     * On fait donc un reset.
     */
    response.reset();
    response.setContentType("text/HTML");
    PrintWriter errorHTMLPage = response.getWriter();
    errorHTMLPage.println("<html>");
    errorHTMLPage.println("  <head>");
    errorHTMLPage.println("    <title>Erreur</title>");
    errorHTMLPage.println("  </head>");
    errorHTMLPage.println("  <body bgcolor=\"ivory\">");
    errorHTMLPage.println("    <center>");
    if (nomClient.length() > 0 || prenomClient.length() > 0)
      errorHTMLPage.println("      <h1>" + prenomClient + " " + nomClient + "</h1>");
    errorHTMLPage.println("      <h3>" + message + "</h3>");
    errorHTMLPage.println("    </center>");
    errorHTMLPage.println("  </body>");
    errorHTMLPage.println("</html>");
  }

}