package controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import manager.ChoiceManager;
import manager.DiplomeMNG;
import manager.DomainManager;
import manager.FormationManager;
import manager.LevelManager;
import manager.PersonalInfoManager;
import manager.PromoManager;
import manager.SkillsManager;
import manager.UniversityMNG;
import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractWizardFormController;
import util.Generator;
import web.FolderForm;
import domain.Choice;
import domain.Diplome;
import domain.Document;
import domain.Folder;
import domain.Formation;
import domain.PersonalInfo;
import domain.Promodetail;
import domain.Skill;
import domain.University;
import domain.logic.InputValidator;
public class UpdateCTRL extends AbstractWizardFormController {
private static Logger logger;
private DomainManager dmmng;
private FormationManager fmng;
// private PromoMNG pmng;
private DiplomeMNG dmng;
private UniversityMNG umng;
private SkillsManager smng;
private LevelManager lmng;
private PersonalInfoManager pimng;
private ChoiceManager cmng;
private PromoManager pdmng;
// private WizardManager wmng;
public PromoManager getPdmng() {
return pdmng;
}
public void setPdmng(PromoManager pdmng) {
this.pdmng = pdmng;
}
public ChoiceManager getCmng() {
return cmng;
}
public void setCmng(ChoiceManager cmng) {
this.cmng = cmng;
}
public PersonalInfoManager getPimng() {
return pimng;
}
public void setPimng(PersonalInfoManager pimng) {
this.pimng = pimng;
}
public FormationManager getFmng() {
return fmng;
}
public void setFmng(FormationManager fmng) {
this.fmng = fmng;
}
public LevelManager getLmng() {
return lmng;
}
public void setLmng(LevelManager lmng) {
this.lmng = lmng;
}
public DomainManager getDmmng() {
return dmmng;
}
public void setDmmng(DomainManager dmmng) {
this.dmmng = dmmng;
}
public SkillsManager getSmng() {
return smng;
}
public void setSmng(SkillsManager smng) {
this.smng = smng;
}
// public WizardManager getWmng() {
// return wmng;
// }
//
// public void setWmng(WizardManager wmng) {
// this.wmng = wmng;
// }
public UniversityMNG getUmng() {
return umng;
}
public void setUmng(UniversityMNG umng) {
this.umng = umng;
}
// public PromoMNG getPmng() {
// return pmng;
// }
//
// public void setPmng(PromoMNG pmng) {
// this.pmng = pmng;
// }
public DiplomeMNG getDmng() {
return dmng;
}
public void setDmng(DiplomeMNG dmng) {
this.dmng = dmng;
}
public UpdateCTRL() {
setCommandName("updatedFoldForm");
setPages(new String[] { "menu", "update-personalinfo",
"update-choices", "update-promodetails", "update-skills",
"update-resume", "update-sum-up" });
setAllowDirtyBack(false);
setAllowDirtyForward(true);
}
@Override
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
HttpSession session = request.getSession(false);
if (session == null)
return new FolderForm();
FolderForm ff = (FolderForm) session.getAttribute("updatedFF");
if (ff == null) {
return new FolderForm();
}
return ff;
}
protected void postProcessPage(HttpServletRequest request, Object command,
Errors errors, int page) throws Exception {
FolderForm ff = (FolderForm) command;
Folder folder = ff.getFolder();
Promodetail current = folder.getCurrentPromoDetail();
String delete = request.getParameter("del");
String edit = request.getParameter("edit");
String action = request.getParameter("action");
String todelete = request.getParameter("delCV");
if (page == 5) {
if (action != null) {
// recuperation du multipart
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile fichier = multipartRequest.getFile("data");
if (fichier.isEmpty()) {
errors.setNestedPath("folder.pi.cv");
errors.rejectValue("data", "cv.data.obligatoire",
"Le document est vide!");
errors.setNestedPath("");
return;
}
String nomDocument = fichier.getOriginalFilename();
if (!nomDocument.endsWith(".pdf")) {
errors.setNestedPath("folder.pi.cv");
errors.rejectValue("data", "data.invalid",
"Seuls les documents 'pdf' sont autoris�s!");
errors.setNestedPath("");
return;
}
if (nomDocument.equals("")) {
errors.setNestedPath("folder.pi.cv");
errors.rejectValue("data", "data.invalid",
"Sp�cifiez un chemin !");
errors.setNestedPath("");
return;
}
String chemin = null;
Document cv = folder.getPi().getCv();
if (!cv.getName().equals("")) {
errors.setNestedPath("folder.pi.cv");
errors.rejectValue("data", "data.invalid",
"Vous avez d�ja envoy� un cv: supprimez le avant!");
errors.setNestedPath("");
return;
}
String id = Generator.getRandomId();
chemin = request.getSession().getServletContext().getRealPath(
"/")
+ "uploads/CV/" + id + "_" + nomDocument;
enregistrer(fichier, chemin);
cv.setName(id + "_" + nomDocument);
} else if (todelete != null) {
System.out.println("DELETING RESUME");
Document cv = folder.getPi().getCv();
File f = new File(request.getSession().getServletContext()
.getRealPath("/")
+ "uploads/CV/" + cv.getName());
f.delete();
cv.setName("");
}
} else if (page == 3) {
if (request.getParameter("add") != null) {
errors.setNestedPath("folder.currentPromoDetail");
String university = request.getParameter("univs");
String diplome = request.getParameter("diplomes");
if (!current.getYear().equals("")) {
try {
Integer.parseInt(current.getYear());
} catch (NumberFormatException nfe) {
errors.rejectValue("year", "year.invalid",
"Type incorrect.");
errors.setNestedPath("");
return;
}
}
if (!current.getRegistered().equals("")) {
try {
Integer.parseInt(current.getRegistered());
} catch (NumberFormatException nfe) {
errors.rejectValue("registered", "registered.invalid",
"Type incorrect.");
errors.setNestedPath("");
return;
}
}
if (!current.getQualified().equals("")) {
try {
Integer.parseInt(current.getQualified());
} catch (NumberFormatException nfe) {
errors.rejectValue("qualified", "qualified.invalid",
"Type incorrect.");
errors.setNestedPath("");
return;
}
}
if (!current.getMark().equals("")) {
try {
Float.parseFloat(current.getMark());
} catch (NumberFormatException nfe) {
errors.rejectValue("mark", "mark.invalid",
"Éssayez xx.5.");
errors.setNestedPath("");
return;
}
}
if (!current.getRank().equals("")) {
try {
Integer.parseInt(current.getRank());
} catch (NumberFormatException nfe) {
errors.rejectValue("rank", "rank.invalid",
"Type incorrect.");
errors.setNestedPath("");
return;
}
}
if (current.isInComplete()) {
errors.setNestedPath("folder");
errors.rejectValue("promodetails", "promodetails.invalid",
"Remplissez tous les champs.");
errors.setNestedPath("");
return;
}
errors.setNestedPath("");
University u = umng.getUniversity(university);
Diplome d = dmng.getDiplomes(diplome);
if (!current.isEmpty()) {
current.setDiplome(d);
current.setUniversity(u);
folder.addPromodetail(current);
}
} else if (request.getParameter("adduniv") != null) {
String nouveau = request.getParameter("newuniv");
/*
* It is very difficult to check the validity of variable
* 'newuniv' Whe just check if 'nouveau' is not empty.
*/
if (!nouveau.equals("")) {
University university = new University();
university.setLabel(nouveau.toUpperCase());
umng.add(university);
}
} else if (request.getParameter("adddegree") != null) {
String nouveau = request.getParameter("newdegree");
/*
* It is very difficult to check the validity of variable
* 'newdegree' Whe just check if 'nouveau' is not empty.
*/
if (!nouveau.equals("")) {
Diplome diplome = new Diplome();
diplome.setLabel(nouveau.toUpperCase());
dmng.add(diplome);
}
} else if (delete != null) {
int index = Integer.parseInt(delete);
List promos = ff.getFolder().getPromodetails();
ff.getFolder().deletePromodetail(index);
} else if (edit != null) {
// folder.setCurrentPromoDetail((Promodetail)folder.getPromodetails().get(Integer.parseInt(edit)));
}
}
}
@SuppressWarnings("unchecked")
protected Map referenceData(HttpServletRequest request, Object command,
Errors errors, int page) throws Exception {
Map model = new HashMap();
Folder folder = ((FolderForm) command).getFolder();
if (page == 1) {
List sexes = new ArrayList();
sexes.add("M");
sexes.add("F");
List nationalities = new ArrayList();
nationalities.add("FRANCAIS");
nationalities.add("ETRANGER");
model.put("nationalities", nationalities);
model.put("sexes", sexes);
} else if (page == 2) {
List formations = fmng.getAllFormations();
model.put("formations", formations);
List formationsWithNone = fmng.getAllFormations();
Formation f = new Formation();
f.setLabel("");
formationsWithNone.add(0, f);
model.put("formationsWithNone", formationsWithNone);
} else if (page == 3) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
List years = new ArrayList();
for (int i = year; i > 1979; i--) {
years.add(i);
System.out.println(i);
}
List diplomes = dmng.getDiplomes();
List univs = umng.getUniversities();
FolderForm folderFormPromoDetails = (FolderForm) command;
Folder folderPromoDetail = folderFormPromoDetails.getFolder();
List promos = folder.getPromodetails();
folder.setNbPromodetails(promos.size());
model.put("diplomes", diplomes);
model.put("univs", univs);
model.put("promos", promos);
model.put("years", years);
} else if (page == 4) {
List domains = dmmng.getAllDomains();
model.put("domains", domains);
List levels = lmng.getAllLevels();
model.put("levels", levels);
for (Iterator iter = folder.getSkills().iterator(); iter.hasNext();) {
Skill skill = (Skill) iter.next();
System.out.println(skill.getId() + " skill avec comment : "
+ skill.getComment());
}
} else if (page == 5 || page == 6) {
model.put("folder", folder);
List domains = dmmng.getAllDomains();
model.put("domains", domains);
}
return model;
}
protected ModelAndView processFinish(HttpServletRequest request,
HttpServletResponse response, Object command, BindException be)
throws Exception {
Folder folder = (Folder) ((FolderForm) command).getFolder();
PersonalInfo pi = folder.getPi();
pi.setState(Folder.FOLDER_SAVED);
/** Reversing the birth date */
String[] birthOld = pi.getBirthdate().split("-");
String birth = birthOld[2] + "-" + birthOld[1] + "-" + birthOld[0];
pi.setBirthdate(birth);
for (Iterator iter = folder.getPromodetails().iterator(); iter.hasNext();) {
Promodetail p = (Promodetail) iter.next();
p.setPersonalinfo_ref(folder.getPi().getId());
}
pdmng.savePromoDetails(folder.getPromodetails());
cmng.saveChoices(folder.getChoices());
smng.saveSkills(folder.getSkills());
pimng.savePersonalInfo(pi);
Map model = new HashMap();
model.put("folder", folder);
return new ModelAndView("update-finished", model);
}
@Override
protected void validatePage(Object command, Errors errors, int page) {
FolderForm folderForm = (FolderForm) command;
InputValidator inputValidator = (InputValidator) getValidator();
switch (page) {
case 1:
errors.setNestedPath("folder.pi");
inputValidator.validatePageOne(folderForm.getFolder().getPi(),
errors);
break;
case 2:
errors.setNestedPath("folder");
inputValidator.validatePageTwo(folderForm.getFolder(), errors);
break;
default:
break;
}
errors.setNestedPath("");
}
private void enregistrer(MultipartFile file, String path)
throws IllegalStateException {
try {
file.transferTo(new File(path));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(byte[].class,
new ByteArrayMultipartFileEditor());
}
}