package junitparams.internal;

import java.lang.reflect.*;

/**
 * Some String utils to handle parameterised tests' results.
 * 
 * @author Pawel Lipinski
 */
public class Utils {

    public static String stringify(Object paramSet, int paramIdx) {
        String result = "[" + paramIdx + "] ";

        if (paramSet instanceof String)
            result += paramSet;
        else
            result += asCsvString(safelyCastParamsToArray(paramSet), paramIdx);

        return trimSpecialChars(result);
    }

    private static String trimSpecialChars(String result) {
        return result.replace(System.getProperty("line.separator"), " ")
                .replace('(', '[').replace(')', ']');
    }

    static Object[] safelyCastParamsToArray(Object paramSet) {
        Object[] params;
        try {
            params = (Object[]) paramSet;
        } catch (ClassCastException e) {
            params = new Object[] { paramSet };
        }
        return params;
    }

    private static String asCsvString(Object[] params, int paramIdx) {
        if (params.length == 0)
            return "";

        String result = "";
        Object lastParam = params[params.length - 1];

        for (Object param : params) {
            result = addParamToResult(result, param);

            if (param != lastParam)
                result += ", ";
        }

        return result;
    }

    private static String addParamToResult(String result, Object param) {
        if (param == null)
            result += "null";
        else {
            try {
                tryFindingOverridenToString(param);
                result += param.toString();
            } catch (Exception e) {
                result += param.getClass().getSimpleName();
            }
        }
        return result;
    }

    private static void tryFindingOverridenToString(Object param)
            throws NoSuchMethodException {
        final Method toString = param.getClass().getMethod("toString");

        if (toString.getDeclaringClass().equals(Object.class)) {
            throw new NoSuchMethodException();
        }
    }
}

@@ -1126,24 +1126,25 @@
 t = %22%22;%0A
+%0A
         
 Object l
@@ -1139,34 +1139,28 @@
     
-Object lastParam = params%5B
+for (int i = 0; i %3C 
 para
@@ -1176,11 +1176,16 @@
  - 1
-%5D;%0A
+; i++) %7B
 %0A   
@@ -1189,21 +1189,20 @@
         
-for (
+    
 Object p
@@ -1210,19 +1210,20 @@
 ram 
-:
+=
  params
-) %7B
+%5Bi%5D;
 %0A   
@@ -1271,18 +1271,24 @@
 , param)
+ + %22, %22
 ;
-%0A
 %0A       
@@ -1292,77 +1292,79 @@
     
-    if (param != lastParam)%0A                result += %22, %22;%0A        %7D
+%7D%0A        result = addParamToResult(result, params%5Bparams.length - 1%5D);
 %0A%0A  

fix for the situation where 2 consecutive parameters have the same value - they weren't separated by a comma then