package test.org.mule.routing;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mule.DefaultMuleMessage;
import org.mule.api.MuleContext;
import org.mule.api.MuleException;
import org.mule.api.MuleMessage;
import org.mule.api.context.MuleContextAware;
import org.mule.api.interceptor.Interceptor;
import org.mule.api.interceptor.Invocation;
import org.mule.tck.functional.FunctionalTestNotification;

import com.example.mule.util.MuleExampleUtils;

public class MockInterceptor implements Interceptor, MuleContextAware {

    public static final int SUCCESS   = 100001;
    public static final int FAILURE   = 100002;
    public static final int EXCEPTION = 100003;

    static final Log log = LogFactory.getLog(MockInterceptor.class);

    MuleContext context;

    public void setMuleContext(MuleContext context) {
        this.context = context;
    }

    public MuleMessage intercept(Invocation invocation) throws MuleException {
        MuleMessage message = invocation.getMessage();
        if (log.isInfoEnabled()) {
            MuleExampleUtils.logMessage(log, "Intercept: ", message);
        }
        Object payload = message.getPayload();
        if (payload instanceof Object[]) {
            Object[] array = (Object[]) payload;
            if (array.length == 1) {
                payload = array[0];
            }
        }
        if ("failure@interceptor".equals(payload)) {
            String result = "FAILURE!! (@interceptor)";
            fireNotification(result, FAILURE);
            log.warn(result);
            return new DefaultMuleMessage(result);
        }
        if ("exception@interceptor".equals(payload)) {
            RuntimeException e =
                    new RuntimeException("EXCEPTION!! (@interceptor)");
            log.warn(e);
            fireNotification(e, EXCEPTION);
            throw e;
        }
        log.info("OK!!");
        return invocation.invoke();
    }

    void fireNotification(Object message, int action) throws MuleException {
        context.fireNotification(
                new FunctionalTestNotification(message, action));
    }

}
