package controleur;
import Metier.Livre;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class AddExemplaire extends HttpServlet {
public static final String VUE_RECHERCHE= "/Recherche.jsp";
public static final String VUE_ADD_EXEMPLAIRE = "/privateAcces/AddExemplaire.jsp";
public static final String PARAM_ID = "id";
public static final String ATT_RESULTAT = "resultat";
private Livre livre;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter(this.PARAM_ID);
this.livre = Metier.MetierFactory.getLivreService().getById(id);
request.setAttribute("livre", livre);
this.getServletContext().getRequestDispatcher(this.VUE_ADD_EXEMPLAIRE).forward( request, response );
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = getServletConfig().getServletContext();
HttpSession session = request.getSession();
int ajoutExemplaire = Integer.parseInt(request.getParameter("addExemplaire"));
this.livre.setExemplaire(this.livre.getExemplaire() + ajoutExemplaire);
Metier.MetierFactory.getLivreService().update(this.livre);
List<Livre> livres = (List<Livre>) session.getAttribute("lastRecherche");
for(int i=0; i<livres.size(); i++){
if(livres.get(i).getId().equals(this.livre.getId())){
if(context.getAttribute("nbLivres") != null){
int nbLivres = (int) context.getAttribute("nbLivres");
nbLivres = nbLivres + ajoutExemplaire;
context.setAttribute("nbLivres", nbLivres);
}
livres.set(i, this.livre);
session.setAttribute("lastRecherche", livres);
}
}
String resultat = "<div class=\"alert alert-success alert-dismissable\">\n" +
" <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>\n" +
" Le livre <strong>"+ this.livre.getTitre() +"</strong> a " + ajoutExemplaire + " exemplaire(s) supplementaire, soit <strong>" + this.livre.getExemplaire() + "</strong> au total.\n" +
"</div>";
request.setAttribute(this.ATT_RESULTAT, resultat);
this.getServletContext().getRequestDispatcher(this.VUE_RECHERCHE).forward( request, response );
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}