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

import nuts.core.lang.Classes;
import nuts.core.lang.DynamicClassLoader;
import nuts.core.lang.Strings;

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


/**
 * utility class for bean 
 */
public class Tools {
	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 = Classes.getPackageName(className);
		String cls = Classes.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 = Strings.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());
	}
}
