package io.irontest.core.assertion;

import com.fasterxml.jackson.core.JsonParseException;
import io.irontest.models.TestResult;
import io.irontest.models.assertion.Assertion;
import io.irontest.models.assertion.AssertionVerificationResult;
import io.irontest.models.assertion.JSONEqualAssertionProperties;
import io.irontest.models.assertion.MessageEqualAssertionVerificationResult;

import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;

/**
 * Created by Zheng on 7/12/2017.
 */
public class JSONEqualAssertionVerifier extends AssertionVerifier {
    /**
     *
     * @param assertion
     * @param input the JSON string that the assertion is verified against
     * @return
     */
    @Override
    public AssertionVerificationResult _verify(Assertion assertion, Object input) throws Exception {
        JSONEqualAssertionProperties assertionProperties = (JSONEqualAssertionProperties) assertion.getOtherProperties();

        //  validate arguments
        if (assertionProperties.getExpectedJSON() == null) {
            throw new IllegalArgumentException("Expected JSON is null.");
        } else if (input == null) {
            throw new IllegalArgumentException("Actual JSON is null.");
        }

        MessageEqualAssertionVerificationResult result = new MessageEqualAssertionVerificationResult();
        try {
            assertJsonEquals(assertionProperties.getExpectedJSON(), input);
        } catch (IllegalArgumentException e) {
            Throwable c = e.getCause();
            if (c instanceof JsonParseException) {
                throw new IllegalArgumentException(e.getMessage() + " " + c.getMessage());
            } else {
                throw e;
            }
        } catch (AssertionError ae) {
            result.setDifferences(ae.getMessage());
        }

        if (result.getDifferences() == null) {
            result.setResult(TestResult.PASSED);
        } else {
            result.setResult(TestResult.FAILED);
        }

        return result;
    }
}

@@ -560,16 +560,202 @@
 r %7B%0A
+    private static final String JSON_UNIT_PLACEHOLDER_REGEX = %22#%5C%5C%7B%5B%5C%5Cs%5D*(json-unit%5C%5C.%5B%5E%7D%5D+)%7D%22;%0A    private static final String JSON_UNIT_PLACEHOLDER_DELIMITER_REPLACEMENT = %22%5C%5C$%7B$1%7D%22;%0A%0A
     /**%0A
     
@@ -750,16 +750,16 @@
     /**%0A
-
      *%0A 
@@ -978,25 +978,8 @@
 put)
- throws Exception
  %7B%0A 
@@ -1377,32 +1377,203 @@
 .%22);%0A        %7D%0A%0A
+        String expectedJSON = assertionProperties.getExpectedJSON().replaceAll(%0A                JSON_UNIT_PLACEHOLDER_REGEX, JSON_UNIT_PLACEHOLDER_DELIMITER_REPLACEMENT);%0A
         MessageE
@@ -1707,32 +1707,9 @@
 als(
-assertionProperties.getE
+e
 xpec
@@ -1715,18 +1715,16 @@
 ctedJSON
-()
 , input)

add JSONEqual assertion to MQ step Dequeue action