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

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ProxyUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;

import java.util.ArrayList;
import java.util.List;

import org.apache.velocity.app.event.MethodExceptionEventHandler;

/**
 * @author Raymond Augé
 * @author Peter Shin
 */
public class LiferayMethodExceptionEventHandler
	implements MethodExceptionEventHandler {

	@Override
	public Object methodException(
			@SuppressWarnings("rawtypes") Class clazz, String method,
			Exception e)
		throws Exception {

		StringBundler sb = new StringBundler(9);

		sb.append("Unable to execute method ");
		sb.append(method);
		sb.append(StringPool.SPACE);
		sb.append(StringPool.OPEN_CURLY_BRACE);
		sb.append("exception=");
		sb.append(e);
		sb.append(StringPool.COMMA_AND_SPACE);
		sb.append(getKeyValuePair(clazz));
		sb.append(StringPool.CLOSE_CURLY_BRACE);

		_log.error(sb.toString(), e);

		return null;
	}

	protected String getKeyValuePair(Class<?> clazz) {
		if (clazz == null) {
			return "class=null";
		}

		if (!ProxyUtil.isProxyClass(clazz)) {
			return "className=" + clazz.getName();
		}

		Class<?>[] interfaceClasses = clazz.getInterfaces();

		if (interfaceClasses == null) {
			return "className=" + clazz.getName();
		}

		List<String> proxyInterfaceClassNames = new ArrayList<String>();

		for (Class<?> interfaceClass : interfaceClasses) {
			proxyInterfaceClassNames.add(interfaceClass.getName());
		}

		return "proxyInterfaceClassNames=" +
			StringUtil.merge(
				proxyInterfaceClassNames, StringPool.COMMA_AND_SPACE);
	}

	private static Log _log = LogFactoryUtil.getLog(
		LiferayMethodExceptionEventHandler.class);

}