package com.pictc.converts.primitive;

import java.math.BigDecimal;

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

public class BigDecimalHandler implements TypeHandler<BigDecimal>{
	
	private Class<?>[] converts=new Class<?>[] {BigDecimal.class};
	
	@Override
	public boolean isType(Class<?> type) {
		return BigDecimal.class.equals(type);
	}

	@Override
	public Class<?>[] getConverts() {
		return converts;
	}

	@Override
	public String convert(BigDecimal value) {
		if(value==null) {
			return null;
		}
		return value.toString();
	}

	@Override
	public BigDecimal valueToObject(Object val) {
		if(val==null) {
			return null;
		}
		Class<?> vcs=val.getClass();
		if(isType(vcs)) {
			return BigDecimal.class.cast(val);
		}else {
			try {
				String strVal=val.toString();
				if(!StringUtils.isEmpty(strVal)) {
					return new BigDecimal(strVal);
				}
				return null;
			} catch (Exception e) {
				throw new ConvertException(vcs,val,BigDecimal.class);
			}
		}
	}

}
