package com.kurukurupapa.tryandroid.apt001;

import java.io.PrintWriter;

import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.util.Elements;
import javax.tools.JavaFileObject;
import javax.tools.Diagnostic.Kind;

public class BeanGenerater {
	public void generateSource(Element element,
			ProcessingEnvironment processingEnv) {
		PrintWriter writer = null;
		try {
			String packageName = getPackageName(element, processingEnv);
			String orgName = element.getSimpleName().toString();
			String shortName = orgName + "Bean";
			String className = packageName + "." + shortName;
			JavaFileObject file = processingEnv.getFiler().createSourceFile(
					className);
			writer = new PrintWriter(file.openWriter(), true);
			writer.println("package " + packageName + ";");
			writer.println();
			writer.println("public class " + shortName + " extends " + orgName
					+ " {");
			for (Element sub : element.getEnclosedElements()) {
				if (sub.getKind() != ElementKind.FIELD) {
					continue;
				}
				String name = sub.getSimpleName().toString();
				String type = sub.asType().toString();
				writer.println("    public " + type + " get" + toU(name)
						+ "() {");
				writer.println("        return " + name + ";");
				writer.println("    }");
				writer.println("    public void set" + toU(name) + "(" + type
						+ " " + name + ") {");
				writer.println("        this." + name + " = " + name + ";");
				writer.println("    }");
			}
			writer.println("}");
			writer.close();
		} catch (Exception e) {
			Messager messager = processingEnv.getMessager();
			messager.printMessage(Kind.ERROR, e.toString());
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}

	private String getPackageName(Element element,
			ProcessingEnvironment processingEnv) {
		Elements elements = processingEnv.getElementUtils();
		PackageElement pe = elements.getPackageOf(element);
		return pe.getQualifiedName().toString();
	}

	private static String toU(String str) {
		char c = str.charAt(0);
		return new StringBuilder().append(String.valueOf(c).toUpperCase())
				.append(str.substring(1)).toString();
	}

}
