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

import java.util.Map;
import java.util.Map.Entry;

import nuts.core.lang.ClassUtils;
import nuts.core.lang.DynamicClassLoader;
import nuts.core.lang.StringUtils;


/**
 * utility class for bean 
 */
public class BeanUtils {
	private static DynamicClassLoader dynamicClassLoader = new DynamicClassLoader();
	
	/**
	 * create dynamic bean class 
	 * @param className class name
	 * @param properties properties
	 * @return bean class
	 * @throws Exception if an error occurs
	 */
	public static Class createBeanClass(String className, Map<String, String> properties) throws Exception {
		String pkg = ClassUtils.getPackageName(className);
		String cls = ClassUtils.getShortClassName(className);
		
		StringBuilder src = new StringBuilder();
		
		src.append("package ").append(pkg).append(";\n\n");
		src.append("public class ").append(cls).append(" {\n");

		for (Entry<String, String> e : properties.entrySet()) {
			String n = e.getKey();
			String cn = StringUtils.capitalize(n);
			String t = e.getValue();

			src.append("  private ").append(t).append(' ').append(n).append(";\n");

			src.append("  public ").append(t).append(' ').append("get").append(cn)
				.append("() { return this.").append(n).append("; }\n");

			src.append("  public void ").append("set").append(cn)
				.append('(').append(t).append(" value) { this.")
				.append(n).append(" = value; }\n");
			
			src.append("\n");
		}
		
		src.append("}\n");
		
		return dynamicClassLoader.loadClass(className, src.toString());
	}
}
