package com.pictc.converts.date;

import java.util.Date;

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

public class DateHandler implements TypeHandler<Date>{
	
	private Class<?>[] converts=new Class<?>[] {Date.class};
	

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

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

	@Override
	public Object convert(Date value) {
		if(value==null) {
			return null;
		}
		return value.getTime();
	}

	@Override
	public Date valueToObject(Object val) {
		if(val==null) {
			return null;
		}
		Class<?> vcs=val.getClass();
		if(isType(vcs)) {
			return Date.class.cast(val);
		}else {
			try {
				return new Date(Long.valueOf(val.toString()));
			} catch (Exception e) {
				throw new ConvertException(vcs,val,Date.class);
			}
		}
	}
	

}
