package org.valid4j;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;

import java.util.Arrays;
import java.util.IllegalFormatException;

/**
 * Class that represents a message, but builds the message first upon invocation of toString().
 */
public class Message {

  public static Message describing(final String format, final Object... args) {
    return new Message() {
      @Override
      public String toString() {
        return withFormattedMessage(format, args);
      }
    };
  }

  public static Message describingMismatchOf(final Object actual, final Matcher<?> matcher) {
    return new Message() {
      @Override
      public String toString() {
        return withMismatchMessageOf(actual, matcher);
      }
    };
  }

  private static String withFormattedMessage(String msg, Object... values) {
    try {
      if (msg != null) {
        return String.format(msg, values);
      } else if (values.length > 0) {
        return fallbackFormattingOf("null", values);
      } else {
        return null;
      }
    } catch (IllegalFormatException e) {
      return fallbackFormattingOf(msg, values);
    }
  }

  private static String withMismatchMessageOf(Object actual, Matcher<?> matcher) {
    Description mismatchDescription = new StringDescription().
        appendText("expected: ").
        appendDescriptionOf(matcher).
        appendText("\n but: ");
    matcher.describeMismatch(actual, mismatchDescription);
    return mismatchDescription.toString();
  }
  
  private static String fallbackFormattingOf(String msg, Object... values) {
    return new StringBuilder(msg).
        append(Arrays.toString(values)).
        toString();
  }
}

@@ -1318,17 +1318,16 @@
 iption()
-.
 %0A       
@@ -1319,32 +1319,33 @@
 ption()%0A        
+.
 appendText(%22expe
@@ -1352,17 +1352,16 @@
 cted: %22)
-.
 %0A       
@@ -1357,24 +1357,25 @@
  %22)%0A        
+.
 appendDescri
@@ -1390,17 +1390,16 @@
 matcher)
-.
 %0A       
@@ -1395,24 +1395,25 @@
 er)%0A        
+.
 appendText(%22
@@ -1534,11 +1534,9 @@
   %7D%0A
-  
 %0A
+
   pr
@@ -1641,17 +1641,16 @@
 der(msg)
-.
 %0A       
@@ -1650,16 +1650,17 @@
         
+.
 append(A
@@ -1682,17 +1682,16 @@
 values))
-.
 %0A       
@@ -1691,16 +1691,17 @@
         
+.
 toString

Change formatting