package com.example.mule.util;

import java.lang.reflect.Array;

import org.apache.commons.logging.Log;
import org.mule.api.ExceptionPayload;
import org.mule.api.MuleMessage;

public class MuleExampleUtils {

    MuleExampleUtils() {}

    public static void logMessage(
            Log log, String prefix, MuleMessage message) {
        if (!log.isInfoEnabled()) {
            return;
        }
        log.info(prefix + message);
        logPayload(log, prefix, message.getPayload());
        ExceptionPayload ep = message.getExceptionPayload();
        if (ep != null) {
            log.info("exception: " + ep.getException());
            log.info("root exception: " + ep.getRootException());
        }
    }

    public static void logPayload(
            Log log, String prefix, Object payload) {
        if (!log.isInfoEnabled()) {
            return;
        }
        if (payload == null) {
            log.info(prefix + payload);
        } else {
            log.info(prefix + "(" +
                    getTypeName(payload.getClass()) + ") " +
                    toString(payload));
        }
    }

    public static String getTypeName(Class<?> clazz) {
        if (clazz.isPrimitive()) {
            return clazz.getSimpleName();
        }
        if (clazz.isArray()) {
            Class<?> componentType = clazz.getComponentType();
            return getTypeName(componentType) + "[]";
        }
        return clazz.getName();
    }

    public static String toString(Object obj) {
        if (obj == null) {
            return null;
        }
        Class<?> clazz = obj.getClass();
        if (!clazz.isArray()) {
            return obj.toString();
        }
        int length = Array.getLength(obj);
        if (length == 0) {
            return "[]";
        }
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (int i = 0; i < length; ++i) {
            sb.append(toString(Array.get(obj, i)));
            sb.append(", ");
        }
        sb.setLength(sb.length() - 2);
        sb.append(']');
        return sb.toString();
    }

}
