package com.atlassian.bitbucket.smtp;

import com.atlassian.bitbucket.async.WaitCondition;
import org.hamcrest.Description;
import org.hamcrest.Matcher;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

class EmailCapturingWaitCondition implements WaitCondition {
    private final SmtpServer smtpServer;
    private final Matcher<MimeMessage> emailMatcher;

    private MimeMessage matchingEmail;

    public EmailCapturingWaitCondition(SmtpServer smtpServer, Matcher<MimeMessage> emailMatcher) {
        this.smtpServer = smtpServer;
        this.emailMatcher = emailMatcher;
    }

    @Override
    public boolean test() {
        matchingEmail = findMatchingEmail();
        return matchingEmail != null;
    }

    @Override
    public void describeFailure(Description desc) throws MessagingException {
        desc.appendText("Unable to find ");
        emailMatcher.describeTo(desc);
        desc.appendText("\nReceived ");
        desc.appendText(MailTestUtils.asFormattedString(smtpServer.getReceivedEmails()));
    }

    /**
     * @return the first email that the given Matcher matches or null if there was no match
     */
    public MimeMessage getMatchingEmail() {
        return matchingEmail;
    }

    private MimeMessage findMatchingEmail() {
        for (MimeMessage message : smtpServer.getReceivedEmails()) {
            if (emailMatcher.matches(message)) {
                return message;
            }
        }
        return null;
    }
}
