/*
 * 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 nuts.aems.constant.RC;
import nuts.aems.constant.TPL;
import nuts.aems.model.bean.User;
import nuts.aems.model.dao.UserDAO;

import java.util.Calendar;

import org.apache.commons.mail.EmailException;

/**
 * AccountAction
 */
public class AccountAction extends RegisterAction {

	/**
	 * Constructor
	 */
	public AccountAction() {
		super();
	}

	/**
	 * check email
	 * @return true/false
	 * @throws Exception
	 */
	protected boolean checkEmail() throws Exception {
		User c = utils().getLoginUser();
		if (c.getEmail().equals(user.getEmail())) {
			return true;
		}

		return super.checkEmail();
	}

	/**
	 * input
	 * @return result name
	 * @throws Exception if an error occurs
	 */
	public String input() throws Exception {
		User c = utils().getLoginUser();

		user = c.clone();
		return INPUT;
	}

	/**
	 * update
	 * @return result name
	 * @throws Exception if an error occurs
	 */
	public String update() throws Exception {
		if (!checkEmail()) {
			return INPUT;
		}

		UserDAO dao = new UserDAO(getDataAccessSession());
		User lu = utils().getLoginUser();

		user.setId(lu.getId());
		user.setPassword(lu.getPassword());
		user.setGroupLevel(lu.getGroupLevel());
		user.setGroupPermits(lu.getGroupPermits());
		user.setInvalid(lu.getInvalid());
		user.setUusid(lu.getId());
		user.setUtime(Calendar.getInstance().getTime());

		dao.update(user);

		if (!lu.getEmail().equals(user.getEmail())) {
			try {
				utils().sendTemplateMail(user, TPL.MAIL_PROFILE_UPDATE, user);
				addActionMessage(getText("message-mailsent", new String[] { user.getEmail() }));
			}
			catch (EmailException e) {
				String msg = getText(RC.ERROR_SENDMAIL, new String[] { user.getEmail() });
				if (utils().ignoreEmailException()) {
					addActionWarning(msg);
				}
				else {
					addActionError(msg);
					getDataAccessSession().rollback();
					return INPUT;
				}
			}
		}

		getDataAccessSession().commit();

		addActionMessage(getText(RC.MESSAGE_SUCCESS));
		utils().setLoginUser(user);

		return SUCCESS;
	}
}
