/**
 * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * Subscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.portal.workflow;

import com.liferay.portal.security.auth.PrincipalException;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portlet.workflowdefinitions.action.WorkflowDefinitionPermissionChecker;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;

/**
 * @author Brian Wing Shun Chan
 */
public class WorkflowPermissionAdvice {

	public Object invoke(ProceedingJoinPoint proceedingJoinPoint)
		throws Throwable {

		Signature signature = proceedingJoinPoint.getSignature();

		String methodName = signature.getName();

		Object[] arguments = proceedingJoinPoint.getArgs();

		if (methodName.equals(_ASSIGN_WORKFLOW_TASK_TO_USER_METHOD_NAME)) {
			long userId = (Long)arguments[1];

			PermissionChecker permissionChecker =
				PermissionThreadLocal.getPermissionChecker();

			if (permissionChecker.getUserId() != userId) {
				throw new PrincipalException();
			}
		}
		else if (methodName.equals(_DEPLOY_WORKFLOW_DEFINITION_METHOD_NAME)) {
			PermissionChecker permissionChecker =
				PermissionThreadLocal.getPermissionChecker();

			if (!WorkflowDefinitionPermissionChecker.
					canPublishWorkflowDefinition(permissionChecker)) {

				throw new PrincipalException();
			}
		}
		else if (methodName.equals(_UPDATE_ACTIVE_METHOD_NAME)) {
			boolean active = (Boolean)arguments[4];

			if (active) {
				PermissionChecker permissionChecker =
						PermissionThreadLocal.getPermissionChecker();

				if (!WorkflowDefinitionPermissionChecker.
						canPublishWorkflowDefinition(permissionChecker)) {

					throw new PrincipalException();
				}
			}
		}

		return proceedingJoinPoint.proceed();
	}

	private static final String _ASSIGN_WORKFLOW_TASK_TO_USER_METHOD_NAME =
		"assignWorkflowTaskToUser";

	private static final String _DEPLOY_WORKFLOW_DEFINITION_METHOD_NAME =
		"deployWorkflowDefinition";

	private static final String _UPDATE_ACTIVE_METHOD_NAME = "updateActive";

}