/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.kisoonlineapp.jsf;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import org.kisoonlineapp.cdi.KisoOnlineApp;

/**
 *
 * @author berni
 */
//@FacesConverter(value = "calendarConverter")
public abstract class AbstractCalendarConverter implements Converter {

    protected final KisoOnlineApp kisoOnlineApp;

    public AbstractCalendarConverter() {
        this.kisoOnlineApp = new KisoOnlineApp();
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || value.isEmpty()) {
            return null;
        }

        try {
            final SimpleDateFormat sdf = createSimpleDateFormat(context);
            final Date date = sdf.parse(value);
            Calendar cal = kisoOnlineApp.getNow();
            cal.setTime(date);
            return cal;
        } catch (ParseException pex) {
            throw new ConverterException("Cannot parse " + value, pex);
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component,
            Object value) {
        String valueAsString = "";
        if (value != null && value instanceof Calendar) {
            Calendar calendar = (Calendar) value;
            final SimpleDateFormat sdf = createSimpleDateFormat(context);
            valueAsString = sdf.format(calendar.getTime());
        }
        return valueAsString;
    }

    protected abstract SimpleDateFormat createSimpleDateFormat(FacesContext context);

}
