/*
 * 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.usergroup;

import nuts.aems.model.bean.User;
import nuts.aems.model.bean.UserGroup;


/**
 * UserGroupExAction
 */
public class UserGroupExAction extends UserGroupAction {

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

	private boolean checkGroupOnInsert(UserGroup ug) {
		User lu = utils().getLoginUser();
		if (!utils().isAdminUser(lu)) {
			if (lu.getGroupLevel() >= ug.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(UserGroup data) throws Exception {
		if (!checkGroupOnInsert(data)) {
			return false;
		}
		return super.checkOnInsert(data);
	}

	private boolean checkGroupOnUpdate(UserGroup nug, UserGroup oug) {
		User lu = utils().getLoginUser();
		if (!utils().isAdminUser(lu)) {
			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(UserGroup data, UserGroup srcData) throws Exception {
		if (!checkGroupOnUpdate(data, srcData)) {
			return false;
		}
		return super.checkOnUpdate(data, srcData);
	}

	private boolean checkGroupOnDelete(UserGroup ug) {
		User lu = utils().getLoginUser();
		if (!utils().isAdminUser(lu)) {
			if (lu.getGroupLevel() >= ug.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(UserGroup data, UserGroup srcData) throws Exception {
		if (!checkGroupOnDelete(srcData)) {
			return false;
		}
		return super.checkOnDelete(data, srcData);
	}
}