package io.jsonwebtoken.lang;

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

/**
 * Local runtime compatibility shim for JJWT 0.12.x.
 */
public final class DateFormats {

  private static final TimeZone UTC = TimeZone.getTimeZone("UTC");

  private static final ThreadLocal<DateFormat> ISO_8601 = ThreadLocal.withInitial(() -> {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    dateFormat.setTimeZone(UTC);
    return dateFormat;
  });

  private static final ThreadLocal<DateFormat> ISO_8601_MILLIS = ThreadLocal.withInitial(() -> {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    dateFormat.setTimeZone(UTC);
    return dateFormat;
  });

  private DateFormats() {
  }

  public static String formatIso8601(Date date) {
    return formatIso8601(date, true);
  }

  public static String formatIso8601(Date date, boolean millis) {
    return (millis ? ISO_8601_MILLIS : ISO_8601).get().format(date);
  }

  public static Date parseIso8601Date(String value) throws ParseException {
    if (value == null) {
      throw new IllegalArgumentException("String argument cannot be null.");
    }
    return (value.lastIndexOf('.') > -1 ? ISO_8601_MILLIS : ISO_8601).get().parse(value);
  }
}
