/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.aems.action.user;

import java.util.List;

import nuts.aems.action.AbstractAction;
import nuts.aems.constant.RC;
import nuts.aems.constant.TPL;
import nuts.aems.model.bean.User;
import nuts.aems.model.dao.UserDAO;
import nuts.aems.model.example.UserExample;

import org.apache.commons.mail.EmailException;



/**
 * PasswordReturnAction
 */
public class PasswordReturnAction extends AbstractAction {

	private String email;

	/**
	 * @return the email
	 */
	public String getEmail() {
		return email;
	}

	/**
	 * @param email the email to set
	 */
	public void setEmail(String email) {
		this.email = email;
	}

	/**
	 * send
	 * @return result name
	 * @throws Exception if an error occurs
	 */
    public String send() throws Exception {
    	UserDAO dao = new UserDAO(getDataAccessSession());
    	UserExample example = new UserExample();
    	
    	example.email().equalTo(email);

    	List<User> list = dao.selectByExample(example);
    	
    	if (list == null || list.size() < 1) {
    		addActionError(getText("error-email-not-registered"));
    		return INPUT;
    	}

		User user = list.get(0);
		try {
			utils().sendTemplateMail(user, TPL.MAIL_PASSWORD_RETURN, user);
		}
		catch (EmailException e) {
			String msg = getText(RC.ERROR_SENDMAIL, new String[] { user.getEmail() });
			addActionError(msg);
			return INPUT;
		}

		addActionMessage(getText(RC.MESSAGE_SUCCESS, new String[] { user.getEmail() }));
		return SUCCESS;
    }

}