package com.ejie.aa21b.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.format.Formatter;

/**
 * DNCG4FormatoFecha
 * 
 *  
 * 
 */
public final class Aa21bFormatoFecha implements Formatter<Date> {

	private String pattern;

	/**
	 * Method 'Aa21bFormatoFecha'. Constructor
	 * 
	 * @param pattern
	 *            String
	 */
	//public Aa21bFormatoFecha(String pattern) {
	//	this.pattern = pattern;
	//}

	//public Aa21bFormatoFecha() {
	//	this.pattern = "dd/MM/yyyy";
	//	try {
	//		if (Aa21bConstantes.AA21B_IDIOMA_EUS.equalsIgnoreCase(LocaleContextHolder.getLocale().getLanguage())) {
	//			this.pattern = "yyyy/MM/dd";
	//		}
	//	} catch(Exception e) {}
	//}
	
	public Aa21bFormatoFecha(boolean conHora) {
		this.pattern = "dd/MM/yyyy";
		try {
			if (Aa21bConstantes.AA21B_IDIOMA_EUS.equalsIgnoreCase(LocaleContextHolder.getLocale().getLanguage())) {
				this.pattern = "yyyy/MM/dd";
			}
		} catch(Exception e) {}
		if (conHora) {
			this.pattern.concat(" HH:mm:ss");
		}
	}

	/**
	 * Method 'print'
	 * 
	 * @param date
	 *            Date
	 * @param locale
	 *            Locale
	 * 
	 * @return String
	 */
	public String print(Date date, Locale locale) {
		if (date == null) {
			return "";
		}
		return this.getDateFormat(locale).format(date);
	}

	/**
	 * Method 'parse'
	 * 
	 * @param formatted
	 *            String
	 * @param locale
	 *            Locale
	 * 
	 * @return Date
	 * 
	 * @throws ParseException
	 *             Exception
	 */
	public Date parse(String formatted, Locale locale) throws ParseException {
		if (formatted.length() == 0) {
			return null;
		}
		return this.getDateFormat(locale).parse(formatted);
	}

	/**
	 * Method 'getDateFormat'
	 * 
	 * @param locale
	 *            Locale
	 * @return DateFormat
	 */
	protected DateFormat getDateFormat(Locale locale) {
		DateFormat dateFormat = new SimpleDateFormat(this.pattern, locale);
		dateFormat.setLenient(false);
		return dateFormat;
	}

}