/*
 * This file is part of DebGen Biobank Software developed by ASTRID Research.
 * All rights reserved. Reproduction, modification, use or disclosure
 * to third parties without express authority is forbidden.
 *
 * Copyright ASTRID Research Inc., Hungary, 2009-2011.
 *
 * ASTRID Research
 * Headquaters: Csapo utca 42. Debrecen H-4029 HUNGARY
 * Phone: +36-52-533-173        Fax: +36-52-533-174
 * Web: http://www.astrid.hu    E-mail: info@astrid.hu
 *
 * Project name: DebGen Biobank Software project.
 * URLS:
 * Developers: Istvan Zoltan Nagy (istvan.nagy@astrid.hu)
 */
package hu.astrid.debgen.forgottenpassword.facade;

import hu.astrid.debgen.forgottenpassword.service.ForgottenPasswordService;
import hu.astrid.debgen.mail.service.SendEmailService;
import hu.astrid.debgen.server.startup.ApplicationParameters;
import hu.astrid.debgen.authentication.domain.DebGenUser;
import hu.astrid.debgen.forgottenpassword.domain.ForgottenPasswordEntry;
import hu.astrid.debgen.localization.service.LocalizationService;
import hu.astrid.toucan.control.persistence.DatabaseServiceClass;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import org.hibernate.Session;

/**
 * The facade which handles the forgotten password operations
 * @author inagy
 */
public class ForgottenPasswordFacade extends DatabaseServiceClass {

    /**
     * Sends a password reminder e-mail to the users mailbox
     * @param email The email address of the user
     * @throws Exception When no such user found or DB fails...
     */
    public void requestNewPassword(String email) throws Exception {
        Session session = null;
        try {
            session = startSession();
            session.beginTransaction();
            ForgottenPasswordService service = getService(session);
            HashMap<ForgottenPasswordEntry, DebGenUser> result = service.requestNewPassword(email);
            Iterator<Entry<ForgottenPasswordEntry, DebGenUser>> iterator = result.entrySet().iterator();
            ForgottenPasswordEntry entry = null;
            DebGenUser user = null;
            if (iterator.hasNext()) {
                Entry<ForgottenPasswordEntry, DebGenUser> next = iterator.next();
                entry = next.getKey();
                user = next.getValue();
            }
            sendConfirmEmail(user, entry);
            session.getTransaction().commit();
        } catch (Exception ex) {
            rollback();
            throw ex;
        } finally {
            closeSession();
        }
    }

    /**
     * Confirms the password reset operation
     * @param userName The name of the user.
     * @param confirmCode The confirmCode of this reset request.
     * @throws Exception When no such user or reset request found or DB fails...
     */
    public void confirmPassword(String userName, String confirmCode) throws Exception {
        Session session = null;
        try {
            session = startSession();
            session.beginTransaction();
            ForgottenPasswordService service = getService(session);
            service.confirmPassword(userName, confirmCode);
            session.getTransaction().commit();
        } catch (Exception ex) {
            rollback();
            throw ex;
        } finally {
            closeSession();
        }
    }

    /**
     * Cancels the password reset operation
     * @param userName The name of the user.
     * @param cancelCode The cancelCode of this reset request.
     * @throws Exception When no such user or reset request found or DB fails...
     */
    public void cancelPassword(String userName, String cancelCode) throws Exception {
        Session session = null;
        try {
            session = startSession();
            session.beginTransaction();
            ForgottenPasswordService service = getService(session);
            service.cancelPassword(userName, cancelCode);
            session.getTransaction().commit();
        } catch (Exception ex) {
            rollback();
            throw ex;
        } finally {
            closeSession();
        }
    }

    /**
     * Gets a new ForgottenPasswordService using a Session
     * @param session The session
     * @return the new service
     */
    private ForgottenPasswordService getService(Session session) {
        ForgottenPasswordService service = (ForgottenPasswordService) ForgottenPasswordService.getInstance(session);
        return service;
    }

    /**
     * Sends a confirm e-mail to the users mailbox
     * @param user The user object
     * @param entry The password reset request entry
     * @throws Exception When the operation is not successful.
     */
    private void sendConfirmEmail(DebGenUser user, ForgottenPasswordEntry entry) throws Exception {
        HashMap<String, String> data = new HashMap<String, String>();
        String applicationName = new LocalizationService().getMessage(ApplicationParameters.getApplicationName(), user.getLanguageISOCode());
        data.put("subject", "[" + applicationName + new LocalizationService().getMessage("] Jelszó visszaállítása", user.getLanguageISOCode()));
        data.put("fullName", user.getFullName());
        data.put("confirmAddress", ApplicationParameters.getApplicationURL() + "/confirmpassword.html?userName=" + user.getUserName() + "&confirmCode=" + entry.getConfirmCode());
        data.put("cancelAddress", ApplicationParameters.getApplicationURL() + "/cancelpassword.html?userName=" + user.getUserName() + "&cancelCode=" + entry.getCancelCode());
        SendEmailService service = new SendEmailService();
        service.sendMail(ForgottenPasswordService.class.getResource("/hu/astrid/debgen/mail/template/"+user.getLanguageISOCode()+"/forgottenpassword.html"),
                data, user.getEmail());
    }
}
