/*
 * 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.model.bean.User;
import nuts.aems.model.bean.UserGroup;
import nuts.aems.model.dao.UserGroupDAO;
import nuts.exts.struts2.util.StrutsContextUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.PreResultListener;



/**
 * UserExAction
 */
public class UserExAction extends UserAction {

	/**
	 * Constructor
	 */
	public UserExAction() {
		super();
	}
	
	public void prepare() throws Exception {
		ActionInvocation invocation = StrutsContextUtils.getActionInvocation();
		invocation.addPreResultListener(new PreResultListener() {
			public void beforeResult(ActionInvocation invocation,
					String resultCode) {
				User lu = utils().getLoginUser();
				if (lu != null && !utils().isAdminUser(lu)) {
					if (getData() != null && getData().getGroupId() != null) {
						UserGroup tug = getUserGroup(getData());
						if (!lu.getId().equals(getData().getId())
								&& lu.getGroupLevel() >= tug.getLevel()) {
							getData().setPassword("******");
						}
					}
					if (getDataList() != null) {
						for (User u : getDataList()) {
							UserGroup tug = getUserGroup(u);
							if (!lu.getId().equals(u.getId())
									&& lu.getGroupLevel() >= tug.getLevel()) {
								u.setPassword("******");
							}
						}
					}
				}
			}
		});
	}

	protected Map<Long, UserGroup> userGroupMap = new HashMap<Long, UserGroup>();
	
	protected UserGroup getUserGroup(User user) {
		UserGroup ug = userGroupMap.get(user.getGroupId());
		if (ug == null) {
			UserGroupDAO ugdao = new UserGroupDAO(getDataAccessSession());
			ug = ugdao.fetch(user.getGroupId());
			if (ug == null) {
				throw new RuntimeException("UserGroup(ID: " + user.getGroupId() + ") does not exists.");
			}
			userGroupMap.put(ug.getId(), ug);
		}
		return ug;
	}

	protected boolean checkUserOnInsert(User nu) {
		User lu = utils().getLoginUser();
		if (!utils().isAdminUser(lu)) {
			UserGroup nug = getUserGroup(nu);
			if (lu.getGroupLevel() >= nug.getLevel()) {
				addActionError(getText("error-level-power"));
				return false;
			}
		}
		return true;
	}
	
	/**
	 * checkOnInsert
	 * @param data data
	 * @return true if check success
	 * @throws Exception if an error occurs
	 */
	@Override
	protected boolean checkOnInsert(User data) throws Exception {
		if (!checkUserOnInsert(data)) {
			return false;
		}
		return super.checkOnInsert(data);
	}

	protected boolean checkUserOnUpdate(User nu, User ou) {
		User lu = utils().getLoginUser();
		if (!utils().isAdminUser(lu)) {
			UserGroup nug = getUserGroup(nu);
			UserGroup oug = getUserGroup(ou);
			if (lu.getGroupLevel() >= nug.getLevel() || lu.getGroupLevel() >= oug.getLevel()) {
				addActionError(getText("error-level-power"));
				return false;
			}
		}
		return true;
	}
	
	/**
	 * checkOnUpdate
	 * @param data data
	 * @param srcData srcData
	 * @return true if check success
	 * @throws Exception if an error occurs
	 */
	@Override
	protected boolean checkOnUpdate(User data, User srcData) throws Exception {
		if (!checkUserOnUpdate(data, srcData)) {
			return false;
		}
		return super.checkOnUpdate(data, srcData);
	}

	protected boolean checkUserOnDelete(User u) {
		User lu = utils().getLoginUser();
		if (!utils().isAdminUser(lu)) {
			UserGroup tug = getUserGroup(u);
			if (lu.getGroupLevel() >= tug.getLevel()) {
				addActionError(getText("error-level-power"));
				return false;
			}
		}
		return true;
	}

	
	/**
	 * checkOnDelete
	 * @param data data
	 * @param srcData srcData
	 * @return true if check success
	 * @throws Exception if an error occurs
	 */
	@Override
	protected boolean checkOnDelete(User data, User srcData) throws Exception {
		if (!checkUserOnDelete(srcData)) {
			return false;
		}

		return super.checkOnDelete(data, srcData);
	}
	
	/**
	 * checkOnBulkDelete
	 * @param data data
	 * @return true - continue, false - skip
	 */
	@Override
	protected boolean checkOnBulkDelete(List<User> dataList) throws Exception {
		super.checkOnBulkDelete(dataList);
		
		for (User u : dataList) {
			if (!checkUserOnDelete(u)) {
				return false;
			}
		}

		return true;
	}
}
