package com.ejie.aa20b.classes;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import com.ejie.x38.util.DateTimeManager;

@Component
public class JsonDateTimeDeserializer extends JsonDeserializer<Date> {

	@Override
	public Date deserialize(JsonParser par, DeserializationContext ctx)
			throws IOException, JsonProcessingException {
		try {
			Locale locale = LocaleContextHolder.getLocale();
			SimpleDateFormat format = DateTimeManager.getDateTimeFormat(locale);

			String dateText = par.getText();

			if ((dateText == null) || ("".equals(dateText))) {
				return null;
			}

			Date date = format.parse(dateText);
			return date;
		} catch (ParseException e) {
			throw new JsonParseException(null, null, e);
		}
	}

}
