/*
 *  Copyright 2013-2050 Emmanuel BRUN (contact@amapj.fr)
 * 
 *  This file is part of AmapJ.
 *  
 *  AmapJ is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.

 *  AmapJ is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with AmapJ.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 
 */
 package fr.amapj.view.views.login.passwordexpired;

import fr.amapj.service.services.authentification.AuthentificationService.CheckResult;
import fr.amapj.service.services.authentification.PasswordComplianceService;
import fr.amapj.service.services.authentification.ProcessSetPasswordService;
import fr.amapj.view.engine.popup.formpopup.WizardFormPopup;
import fr.amapj.view.engine.popup.formpopup.genericmodel.StringItem;
import fr.amapj.view.engine.ui.AmapUI;

/**
 * Popup pour la saisie d'un nouveau password, suite à une non conformité  
 * 
 * TODO voir comment merger avec le code de ProcessSetPasswordPopupSaisiePassword
 *  
 */
public class ExpiredPasswordStep2Popup extends WizardFormPopup
{	
	private StringItem password;

	private AmapUI ui;

	private CheckResult checkResult;
	
	private boolean passwordSuccessfullyUpdated = false;

	/**
	 * 
	 */
	public ExpiredPasswordStep2Popup(AmapUI ui, CheckResult checkResult)
	{
		this.ui = ui;
		this.checkResult = checkResult;
		popupTitle = "Changement de votre mot de passe"; 
		
		password = new StringItem();
		setModel(password);
	}
	
	
	@Override
	protected void configure()
	{
		add(()->addSaisiePassword());
		add(()->addResultat());
	}
	
	
	protected void addSaisiePassword()
	{
		addHtml("Merci de saisir votre nouveau mot de passe ci dessous.");
		
		addPasswordTextField("Votre nouveau mot de passe", "value");
		
		addHtml(new PasswordComplianceService().getHtmlExplanationPasswordCompliant());
	}
	
	private void addResultat()
	{
		passwordSuccessfullyUpdated = new ProcessSetPasswordService().setUserPassword(checkResult.idUtilisateur,password.value,true);
		String msg = passwordSuccessfullyUpdated==true ? "Votre mot de passe a été changé avec succés" : "Impossible de modifier votre mot de passe. Celui ci ne respecte pas les régles de robustesse des mots de passe.";
		addHtml(msg);
		
		setAllButtonsAsOK();
	}

	@Override
	protected void performSauvegarder()
	{
		if (passwordSuccessfullyUpdated)
		{
			ui.buildMainView();
		}
		else
		{
			new ExpiredPasswordStep2Popup(ui, checkResult).open();
		}
	}
}
