package io.wealthwizards.appsynctesting.utils;

import lombok.AllArgsConstructor;

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

@AllArgsConstructor
public final class Time {
    private Instant now;

    public Time() {
        now = Instant.now();
    }

    public String nowISO8601() {
        return DateTimeFormatter.ISO_INSTANT.format(now);
    }

    public long nowEpochSeconds() {
        return now.getEpochSecond();
    }

    public long nowEpochMilliSeconds() {
        return now.toEpochMilli();
    }

    public String nowFormatted(String format) {
        return nowFormatted(format, "+00:00");
    }

    public String nowFormatted(String format, String offset) {
        return DateTimeFormatter.ofPattern(format)
                .withZone(ZoneId.of(offset))
                .format(now);
    }

    public Long parseFormattedToEpochMilliSeconds(String chars, String format) {
        return parseFormattedToEpochMilliSeconds(chars, format, "+0000");
    }

    public Long parseFormattedToEpochMilliSeconds(String chars, String format, String offset) {
        var instant = Instant.from(
                DateTimeFormatter
                        .ofPattern(format)
                        .withZone(ZoneId.of(offset))
                        .parse(chars)
        );

        return instant.toEpochMilli();
    }

    public Long parseISO8601ToEpochMilliSeconds(String chars) {
        var formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;

        return Instant.from(formatter.parse(chars))
                .toEpochMilli();
    }

    public long epochMilliSecondsToSeconds(long millis) {
        var instant = Instant.ofEpochMilli(millis);

        return instant.getEpochSecond();
    }

    public String epochMilliSecondsToISO8601(long millis) {
        var instant = Instant.ofEpochMilli(millis);

        return DateTimeFormatter.ISO_INSTANT.format(instant);
    }

    public String epochMilliSecondsToFormatted(long millis, String format) {
        return epochMilliSecondsToFormatted(millis, format, "+0000");
    }

    public String epochMilliSecondsToFormatted(long millis, String format, String offset) {
        var instant = Instant.ofEpochMilli(millis);

        return DateTimeFormatter.ofPattern(format)
                .withZone(ZoneId.of(offset))
                .format(instant);
    }
}
