package com.ejie.aa20b.classes;

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

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import com.ejie.aa20b.util.Aa20bConstantes;

/**
 * Used to serialize Java.util.Date, which is not a common JSON type, so we have
 * to create a custom serialize method;.
 * 
 * @author Loiane Groner
 */
@Component
public class JsonDateTimeSerializer extends JsonSerializer<Date> {

	// private static final SimpleDateFormat dateFormat = new SimpleDateFormat(
	// "yyyy-MM-dd HH:mm:ss");

	@Override
	public void serialize(Date date, JsonGenerator gen,
			SerializerProvider provider) throws IOException,
			JsonProcessingException {

		SimpleDateFormat sdf = null;
		if (LocaleContextHolder.getLocale().getLanguage()
				.equals(Aa20bConstantes.IDIOMA_EUSKERA)) {
			sdf = new SimpleDateFormat("yyyy/MM/dd");
		} else {
			sdf = new SimpleDateFormat("dd/MM/yyyy");
		}
		String formattedDate = "";
		if (date != null) {
			formattedDate = sdf.format(date);
		}

		gen.writeString(formattedDate);
	}
}