package tw.kewang.hbase.domain;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import tw.kewang.hbase.annotations.Component;
import tw.kewang.hbase.annotations.Rowkey;

public abstract class AbstractDomain {
	private static final String REGEX = "\\{([\\d\\w]+)\\}";

	private ColumnFamily family;
	private ColumnQualifier qualifier;

	public String getRowkey() {
		Class<?> clazz = getClass();

		Rowkey rowkey = clazz.getAnnotation(Rowkey.class);

		if (rowkey != null) {
			return buildRowkey(clazz, rowkey);
		}

		return null;
	}

	private String buildRowkey(Class<?> clazz, Rowkey rowkey) {
		Pattern pattern = Pattern.compile(REGEX);
		String rowkeyPattern = rowkey.value();
		Matcher matcher = pattern.matcher(rowkeyPattern);
		StringBuffer sb = new StringBuffer();

		while (matcher.find()) {
			for (Field field : clazz.getDeclaredFields()) {
				field.setAccessible(true);

				Component component = field.getAnnotation(Component.class);

				if (component.name().equals(matcher.group(1))) {
					try {
						String value = castValue(field, component.classType());

						if (value != null) {
							matcher.appendReplacement(sb, value);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		matcher.appendTail(sb);

		return sb.toString();
	}

	private String castValue(Field field, Class<?> ab) {
		try {
			if (ab.isAssignableFrom(String.class)) {
				return (String) field.get(this);
			} else if (ab.isAssignableFrom(Long.class)) {
				return String.valueOf(field.get(this));
			} else if (ab.isAssignableFrom(Integer.class)) {
				return String.valueOf(field.get(this));
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public ColumnFamily getFamily() {
		return family;
	}

	public void setFamily(ColumnFamily family) {
		this.family = family;
	}

	public ColumnQualifier getQualifier() {
		return qualifier;
	}

	public void setQualifier(ColumnQualifier qualifier) {
		this.qualifier = qualifier;
	}
}
@@ -1382,18 +1382,21 @@
 lass%3C?%3E 
-ab
+clazz
 ) %7B%0A%09%09tr
@@ -1402,26 +1402,29 @@
 ry %7B%0A%09%09%09if (
-ab
+clazz
 .isAssignabl
@@ -1489,34 +1489,37 @@
 ;%0A%09%09%09%7D else if (
-ab
+clazz
 .isAssignableFro
@@ -1593,18 +1593,21 @@
 lse if (
-ab
+clazz
 .isAssig

Modify name