package com.pictc.converts.primitive;

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

public class DoubleHandler implements TypeHandler<Double>{
	
	private Class<?>[] converts=new Class<?>[] {Double.class,double.class};

	@Override
	public boolean isType(Class<?> type) {
		return Double.class.equals(type) || double.class.equals(type);
	}

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

	@Override
	public Object convert(Double value) {
		return doubleToString(value);
	}

	@Override
	public Double valueToObject(Object val) {
		if(val==null) {
			return null;
		}
		Class<?> vcs=val.getClass();
		if(isType(vcs)) {
			return Double.class.cast(val);
		}else if(Number.class.equals(vcs)) {
			return Number.class.cast(val).doubleValue();
		}else {
			try {
				return Double.valueOf(val.toString());
			} catch (Exception e) {
				throw new ConvertException(vcs,val,Double.class);
			}
		}
	}
	
	public static String doubleToString(double d) {
		if (Double.isInfinite(d) || Double.isNaN(d)) {
			return "null";
		}
		String string = Double.toString(d);
		if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) {
			while (string.endsWith("0")) {
				string = string.substring(0, string.length() - 1);
			}
			if (string.endsWith(".")) {
				string = string.substring(0, string.length() - 1);
			}
		}
		return string;
	}

}
