package ru.micord.ervu.util;

import java.time.*;
import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

import static org.springframework.util.StringUtils.hasText;

/**
 * @author gulnaz
 */
public final class DateUtils {
  private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy");
  private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss");
  private static final DateTimeFormatter DATE_TIME_WITH_TIMEZONE_FORMATTER = DateTimeFormatter.ofPattern(
      "yyyy-MM-dd'T'HH:mm:ss.SSSX");

  private DateUtils() {
  }

  public static String getCurrentFormattedDateTimeWithZone(){
    ZonedDateTime now = ZonedDateTime.now();
    return now.format(DATE_TIME_WITH_TIMEZONE_FORMATTER);
  }

  public static String getClientDateTimeWithZoneFromRequest(HttpServletRequest request) {
    String clientTimeZone = request.getHeader("Client-Time-Zone");
    ZoneId zoneId;
    try {
      zoneId = ZoneId.of(clientTimeZone);
    }
    catch (Exception e) {
      zoneId = ZoneId.systemDefault();
    }
    return ZonedDateTime.now(zoneId).format(DATE_TIME_WITH_TIMEZONE_FORMATTER);
  }

  public static LocalDate convertToLocalDate(String date) {
    return StringUtils.hasText(date)
           ? LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE)
           : null;
  }

  public static LocalDateTime convertToLocalDateTime(String dateTime) {
    return hasText(dateTime)
           ? LocalDateTime.parse(dateTime, DATE_TIME_FORMATTER)
           : null;
  }

  public static String convertToString(LocalDateTime dateTime) {
    return dateTime == null ? "" : dateTime.format(DATE_TIME_FORMATTER);
  }

  public static String convertToString(LocalDate date) {
    return date == null ? "" : date.format(DATE_FORMATTER);
  }

  public static String convertToString(LocalDate date, DateTimeFormatter formatter) {
    return date == null ? "" : date.format(formatter);
  }
}
