package test.org.mule.routing;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mule.api.MuleContext;
import org.mule.api.MuleException;
import org.mule.api.context.MuleContextAware;
import org.mule.tck.functional.FunctionalTestNotification;

import com.example.mule.util.MuleExampleUtils;

public class MockComponent implements 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(MockComponent.class);

    MuleContext context;

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

    public Object doSomething(Object arg) throws Exception {
        if (log.isInfoEnabled()) {
            MuleExampleUtils.logPayload(log, "Called: ", arg);
        }
        if ("failure@component".equals(arg)) {
            String result = "FAILURE!! (@component)";
            log.warn(result);
            fireNotification(result, FAILURE);
            return result;
        }
        if ("exception@component".equals(arg)) {
            RuntimeException e =
                    new RuntimeException("EXCEPTION!! (@component)");
            log.warn(e);
            fireNotification(e, EXCEPTION);
            throw e;
        }
        log.info("OK!!");
        fireNotification(arg, SUCCESS);
        return arg;
    }

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

}
