package com.pictc.converts.primitive;

import java.lang.reflect.Method;

import com.pictc.converts.ConvertException;
import com.pictc.converts.TypeHandler;

public class EnumHandler implements TypeHandler<Enum<?>>{
	
	private Class<?> klazz;

	public EnumHandler(Class<?> klazz) {
		super();
		this.klazz = klazz;
	}

	@Override
	public boolean isType(Class<?> type) {
		return type.isEnum();
	}

	@Override
	public Class<?>[] getConverts() {
		return null;
	}
	
	
	@Override
	public Object convert(Enum<?> value) {
		if(value==null) {
			return null;
		}
		return value.toString();
	}

	@SuppressWarnings("unchecked")
	public <T>T valueToObject(Class<T> clazz,Object val) {
		Class<?> vcs=val.getClass();
		if(isType(vcs)) {
			return (T)val;
		}else {
			try {
				Method method=clazz.getMethod("valueOf", String.class);
				return (T) method.invoke(null,val.toString());
			} catch (Exception e) {
				throw new ConvertException(vcs,val,Enum.class);
			}
		}
	}

	@Override
	public Enum<?> valueToObject(Object val) {
		if(val==null) {
			return null;
		}
		Class<?> vcs=val.getClass();
		if(isType(vcs)) {
			return (Enum<?>) val;
		}else {
			try {
				Method method=klazz.getMethod("valueOf", String.class);
				return (Enum<?>)method.invoke(null,val.toString());
			} catch (Exception e) {
				throw new ConvertException(vcs,val,klazz);
			}
		}
	}
	
}
