package com.atlassian.bitbucket.hamcrest;

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class TimeMatchers {

    @Factory
    public static Matcher<Date> closeTo(final Date ref, final int plusOrMinus, final TimeUnit unit) {
        return new TypeSafeMatcher<Date>() {
            @Override
            public boolean matchesSafely(Date date) {
                return Math.abs(ref.getTime() - date.getTime()) < (TimeUnit.MILLISECONDS.convert(plusOrMinus, unit));
            }

            @Override
            public void describeTo(Description description) {
                description.appendText("a date around ").appendValue(ref)
                           .appendText(" plus or minus ").appendValue(plusOrMinus)
                           .appendText(" ").appendText(unit.name().toLowerCase());
            }
        };
    }

}
