/* **********************************************************************
 * source:    MyDateAdapter
 * package:   com.me.my.support
 * author:    sisjo
 ************************************************************************/
package com.me.my.support;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.sql.Time;
import java.sql.Timestamp;

/*************
* class: MyDateAdapter
* <p>
* This is a class to ...
*/
public final class MyDateAdapter extends XmlAdapter<String, MyDateType>
{
    private DateFormat dtFormatter;
    private DateFormat tsFormatter;

    public MyDateAdapter() {
        dtFormatter = new SimpleDateFormat(dateFormat);
        tsFormatter = new SimpleDateFormat(timestampFormat);
    }

    public MyDateType unmarshal(String s) throws Exception {
        Date date;
        try {
            date = dtFormatter.parse(s);
        }
        catch (ParseException ex) {
            try {
                date = tsFormatter.parse(s);
            }
            catch (ParseException ex2) {
                try {
                    date = Time.valueOf(s);
                }
                catch (IllegalArgumentException ex3) {
                    date = nullTimestamp;
                }
            }
        }
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTimeInMillis(date.getTime());
        return new MyDateType(cal);
    }

    public String marshal(MyDateType cal) throws Exception {
        Date date = cal.toGregorianCalendar().getTime();
        if (cal.getHour() == 0
        &&  cal.getMinute() == 0
        &&  cal.getSecond() == 0) {
            return dtFormatter.format(date);
        } else {
            return tsFormatter.format(date);
        }
    }

    public static MyDateAdapter getInstance(String appDateFormat, String appTimestampFormat, Timestamp appNullTimestamp) {
        dateFormat = appDateFormat;
        timestampFormat = appTimestampFormat;
        nullTimestamp = appNullTimestamp;
        return new MyDateAdapter();
    }

    private static String     dateFormat      = "yyyy-MM-dd";
    private static String     timestampFormat = "yyyy-MM-dd HH:mm:ss";
    private static Timestamp  nullTimestamp   = new Timestamp(0);
}
