
package com.wickedcooljava.sci.component;

/*
Example code from Wicked Cool Java (No Starch Press)
Copyright (C) 2005 Brian D. Eubanks

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

Note: The LGPL licence can be found online at http://www.gnu.org

*/
/**
 * This is a pass-through implementation of the Component interface.  
 */
public class BaseComponent<T> implements Component<T> {

	protected int inSize, outSize;

	protected InputPortImpl<T>[] inports;

	protected OutputPortImpl<T>[] outports;

	/// the function performed by this component
	protected ComponentEngine<T> function;

	/**
	 * 
	 * @param inputs Number of input ports
	 * @param outputs Number of output ports
	 * @param f The function to perform the processing
	 */
	public BaseComponent(int inputs, int outputs, ComponentEngine<T> f) {
		inSize = inputs;
		outSize = outputs;
		function = f;
		inports = new InputPortImpl[inSize];
		for (int i = 0; i < inSize; i++) {
			inports[i] = new InputPortImpl<T>(this);
		}
		outports = new OutputPortImpl[outSize];
		for (int i = 0; i < outSize; i++) {
			outports[i] = new OutputPortImpl<T>(this);
		}
	}

	public int getInputSize() {
		return inSize;
	}

	public int getOutputSize() {
		return outSize;
	}

	public InputPort<T> getInputPort(int index) {
		return inports[index];
	}

	public OutputPort<T> getOutputPort(int index) {
		return outports[index];
	}

	/**
	 * Delegate to the engine to do the processing.
	 */
	public void process() {
		function.process(inports, outports);
	}

	public String toString() {
		StringBuffer buf = new StringBuffer();
		buf.append("BaseComponent\n");
		buf.append("Inputs:\n");
		for (PortImpl port : inports) {
			buf.append(port.getValue());
			buf.append("\n");
		}
		buf.append("Outputs:\n");
		for (OutputPort port : outports) {
			buf.append(port.getValue());
			buf.append("\n");
		}
		return buf.toString();
	}

}
