package lc.mecha.time;

import java.time.Duration;
import java.time.Instant;
import java.util.Objects;

public class Interval {
    private final Instant begin;
    private final Instant end;

    public Interval(Instant begin, Instant end) {
        this.begin = begin;
        this.end = end;
    }

    /**
     * Returns <code>true<code> if the provided interval overlaps with this one in any way. The overlap is considered
     * to be inclusive, that is to say, the intervals are considered to overlap if the start and end time is exactly
     * the same.
     *
     * @param t2
     * @return
     */
    public boolean overlap(Interval t2) {
        return end.isBefore(t2.begin) && !begin.isAfter(t2.end);
    }

    public Instant getBegin() {
        return begin;
    }

    public Instant getEnd() {
        return end;
    }

    public Duration duration() {
        return Duration.between(begin, end);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Interval interval = (Interval) o;
        return Objects.equals(begin, interval.begin) &&
                Objects.equals(end, interval.end);
    }

    @Override
    public int hashCode() {
        return Objects.hash(begin, end);
    }

    @Override
    public String toString() {
        return "Interval{" +
                "begin=" + begin +
                ", end=" + end +
                '}';
    }
}
