// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package jcademo.raoutbound.multcp_cci;

import javax.resource.ResourceException;
import javax.resource.cci.Connection;
import javax.resource.cci.IndexedRecord;
import javax.resource.cci.Interaction;
import javax.resource.cci.InteractionSpec;
import javax.resource.cci.MappedRecord;
import javax.resource.cci.Record;
import javax.resource.cci.ResourceWarning;

public class CCI_Interaction implements Interaction {
	// connection
	private TestConnection con;
	public CCI_Interaction(TestConnection con) {
		this.con = con;
	}
	@Override
	public Connection getConnection() {
		return con;
	}
	// execute
	@Override
	public Record execute(InteractionSpec ispec, Record input) throws ResourceException {
		Record output;
		if(input instanceof IndexedRecord) {
			output = new CCI_C_IndexedRecord();
		} else if(input instanceof MappedRecord) {
			output = new CCI_C_MappedRecord();
		} else {
			throw new ResourceException("Unknown record type " + input.getClass().getName());
		}
		return execute(ispec, input, output) ? output : null;
	}
	@Override
	public boolean execute(InteractionSpec ispec, Record input, Record output) throws ResourceException {
		int a;
		int b;
		if(input instanceof IndexedRecord) {
			IndexedRecord input2 = (IndexedRecord)input;
			a = (Integer)input2.get(0);
			b = (Integer)input2.get(1);
		} else if(input instanceof MappedRecord) {
			MappedRecord input2 = (MappedRecord)input;
			a = (Integer)input2.get("A");
			b = (Integer)input2.get("B");
		} else {
			throw new ResourceException("Unknown record type " + input.getClass().getName());
		}
		CCI_InteractionSpec ispec2 = (CCI_InteractionSpec)ispec;
		int c;
		if(ispec2.getFunctionName().equals("ADD")) {
			c = con.add(a, b);
		} else {
			throw new ResourceException("Unknown function name " + ispec2.getFunctionName());
		}
		if(output instanceof IndexedRecord) {
			IndexedRecord output2 = (IndexedRecord)output;
			output2.set(0, c);
		} else if(output instanceof MappedRecord) {
			MappedRecord output2 = (MappedRecord)output;
			output2.put("C", c);
		} else {
			throw new ResourceException("Unknown record type " + output.getClass().getName());
		}
		return true;
	}
	// close
	@Override
	public void close() throws ResourceException {
		// nothing
	}
	// warnings
	@Override
	public ResourceWarning getWarnings() throws ResourceException {
		throw new ResourceException("Warnings not supported");
	}
	@Override
	public void clearWarnings() throws ResourceException {
		throw new ResourceException("Warnings not supported");
	}
}
