
package com.wickedcooljava.sci.component;

import java.util.ArrayList;

/*
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

*/
/**
 * A basic implementation of a Wire. The number of target ports can grow 
 * dynamically, but for performance reasons it will use a single target object 
 * when the first one is added. As more targets are added, an ArrayList is used
 * and is populated with them. 
 */
public class WireImpl<T> implements Wire<T>{

	private OutputPort<T> source;
	// lazy target array
	private ArrayList<InputPort<T>> targetList;
	private InputPort<T> target;
	private int count = 0;
	
	public WireImpl(OutputPort<T> src) {
		source = src;
	}

	public OutputPort<T> getSourcePort() {
		return source;
	}
	
	public int getNumberOfTargetPorts() {
		return count;
	}
	
	public InputPort<T> getTargetPort(int index) {
		if (index >= count || index < 0) {
			throw new IndexOutOfBoundsException();
		}
		if (target != null) {
			return target;
		}
		return targetList.get(index);
	}
	
	public void addTargetPort(InputPort<T> tgt) {
		if (targetList == null) {
			if (target == null) {
				target = tgt;
				count++;
			} else {
				targetList = new ArrayList<InputPort<T>>();
				targetList.add(target);
				target = null;
			}
		}
		if (targetList != null) {
			if (!targetList.contains(tgt)) {
				targetList.add(tgt);
				count++;
			}
		}
	}

	public void propagateSignal() {
		T value = source.getValue();
		if (target == null) {
			if (targetList != null) {
				for (InputPort<T> tgt : targetList) {
					tgt.setValue(value);
				}
			}
		} else {
			target.setValue(value);
		}
	}
}
