package com.hammurapi.reasoning.impl;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

import com.hammurapi.reasoning.ReasoningException;
import com.hammurapi.reasoning.spi.InferenceContext;

/**
 * Delegates calls to thread local 
 * @author Pavel Vlasov
 *
 */
public class InferenceContextDispatcher implements InferenceContext {
	
	private static ThreadLocal<InferenceContext> ictl = new ThreadLocal<InferenceContext>();
	
	static void setThreadInferenceContext(InferenceContext ic) {
		ictl.set(ic);		
	}
	
	static void unsetThreadInferenceContext() {
		ictl.set(null);
	}
	
	private InferenceContext getDelegate() {
		InferenceContext delegate = ictl.get();
		if (delegate==null) {
			throw new IllegalStateException("No inference context is set for current thread.");
		}
		return delegate;		
	}

	public void addUndo(Runnable undoCommand) {
		getDelegate().addUndo(undoCommand);
	}

	public boolean consumeInput(int position, boolean local) {
		return getDelegate().consumeInput(position, local);
	}

	public boolean contains(Object fact) throws ReasoningException {
		return getDelegate().contains(fact);
	}

	public Collection<?> getObjects() throws ReasoningException {
		return getDelegate().getObjects();
	}

	public Map<String, ?> getProperties() throws ReasoningException {
		return getDelegate().getProperties();
	}

	public int[] parameterIndices() {
		return getDelegate().parameterIndices();
	}

	public void post(Object... conclusions) {
		getDelegate().post(conclusions);
	}

	public void remove(Object fact) throws ReasoningException {
		getDelegate().remove(fact);
	}

	public Method targetMethod() {
		return getDelegate().targetMethod();
	}

	@Override
	public void put(Object fact) throws ReasoningException {
		getDelegate().put(fact);		
	}

	@Override
	public void update(Object fact) throws ReasoningException {
		getDelegate().update(fact);
	}

	@Override
	public void update(Object originalFact, Object newFact)	throws ReasoningException {
		getDelegate().update(originalFact, newFact);
	}
}
