package com.mypurecloud.sdk.v2;

import com.google.common.collect.Lists;
import org.joda.time.DateTime;
import org.joda.time.Instant;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

public class JodaApiDateFormat extends DateFormat {

    private final List<DateTimeFormatter> formats;

    public JodaApiDateFormat() {
        setCalendar(Calendar.getInstance(TimeZone.getTimeZone("UTC")));
        setNumberFormat(NumberFormat.getInstance());

        formats = Lists.newArrayList(
                ISODateTimeFormat.dateTimeParser(),
                DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"),
                DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
        );
    }

    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        StringBuffer stringBuffer = new StringBuffer();
        formats.get(0).printTo(stringBuffer, new Instant(date));
        return stringBuffer;
    }

    @Override
    public Date parse(String source, ParsePosition pos) {
        for (DateTimeFormatter format : formats) {
            try {
                DateTime date = format.parseDateTime(source);
                if (date != null) {
                    pos.setIndex(source.length() - 1);
                    return date.toDate();
                }
            } catch (Exception e) {
                // no-op
            }
        }
        return null;
    }
}

@@ -118,23 +118,29 @@
 da.time.
-Instant
+LocalDateTime
 ;%0Aimport
@@ -272,16 +272,17 @@
 ormat;%0A%0A
+%0A
 import j
@@ -413,67 +413,44 @@
 ava.
-u
 ti
-l.Calendar;%0Aimport java.util.Date;%0Aimport java.util.List
+me.format.DateTimeFormatterBuilder
 ;%0Aim
@@ -464,24 +464,17 @@
 va.util.
-TimeZone
+*
 ;%0A%0Apubli
@@ -571,16 +571,167 @@
 formats;
+%0A    private final DateTimePrinter printer = new DateTimeFormatterBuilder()%0A            .append(ISODateTimeFormat.dateTime())%0A            .toPrinter();
 %0A%0A    pu
@@ -967,14 +967,8 @@
 Time
-Parser
 (),%0A
@@ -1249,54 +1249,108 @@
     
-StringBuffer stringBuffer = new StringBuffer
+if (toAppendTo == null) %7B%0A            toAppendTo = new StringBuffer(printer.estimatePrintedLength
 ()
+)
 ;%0A  
@@ -1359,62 +1359,80 @@
     
-formats.get(0).printTo(stringBuffer, new Instant(date)
+%7D%0A        printer.printTo(toAppendTo, new LocalDateTime(date), Locale.US
 );%0A 
@@ -1449,20 +1449,18 @@
 urn 
-stringBuffer
+toAppendTo
 ;%0A  

Fix JodaApiDateFormat.format(Date,StringBuffer,FieldPosition)