package ru.yandex.qe.bus.javatime;

import java.time.Instant;
import java.time.format.DateTimeFormatter;

import javax.ws.rs.ext.ParamConverter;

/**
 * Parses Instant from a valid unix timestamp (seconds from EPOCH) or ISO-formatted datetime;
 * Formats Instant to ISO-format only.
 * @author Alexei Zakharov (ayza)
 */
public class InstantParamConverter implements ParamConverter<Instant> {
  private static DateTimeFormatter ISO_FORMATTER = DateTimeFormatter.ISO_INSTANT;

  @Override
  public Instant fromString(String value) {
    try {
      long longValue = Long.valueOf(value);
      return Instant.ofEpochSecond(longValue);
    } catch (NumberFormatException e) {
      // not a valid UNIX timestamp
      // let's try ISO format
      return ISO_FORMATTER.parse(value, Instant::from);
    }
  }

  @Override
  public String toString(Instant value) {
    return ISO_FORMATTER.format(value);
  }
}
