/**
 * Copyright (c) 2000-present 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.template.freemarker.internal;

import com.liferay.portal.kernel.util.PortalClassLoaderUtil;

import freemarker.ext.beans.BeansWrapper;

import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;

import java.util.List;

/**
 * @author Raymond Augé
 */
public class LiferayObjectConstructor implements TemplateMethodModelEx {

	public LiferayObjectConstructor(BeansWrapper beansWrapper) {
		_beansWrapper = beansWrapper;
	}

	@Override
	public Object exec(@SuppressWarnings("rawtypes") List arguments)
		throws TemplateModelException {

		if (arguments.isEmpty()) {
			throw new TemplateModelException(
				"This method must have at least one argument as the name of " +
					"the class to instantiate");
		}

		String className = String.valueOf(arguments.get(0));

		Thread currentThread = Thread.currentThread();

		Class<?> clazz = null;

		try {
			clazz = Class.forName(
				className, true, currentThread.getContextClassLoader());
		}
		catch (Exception e1) {
			try {
				clazz = Class.forName(
					className, true, PortalClassLoaderUtil.getClassLoader());
			}
			catch (Exception e2) {
				throw new TemplateModelException(e2.getMessage());
			}
		}

		Object object = _beansWrapper.newInstance(
			clazz, arguments.subList(1, arguments.size()));

		return _beansWrapper.wrap(object);
	}

	private final BeansWrapper _beansWrapper;

}