/**
 * This class can be the super class of all DigitalComponents implementing DigitalComponent
 * and implements all the required services (which can be redefined for the daughter). An instance
 * of this class can be used to avoid leaving unconnecting pins on a DigitalComponent.
 * <BR>You can read the source of this class <A HREF="./DigitalComponent_std.java.html"> here</A>.
 */
public class DigitalComponent_std implements DigitalComponent {

	public DigitalComponent_std(int n) {
		Pins = new Pin_std[n];
		NbPins = n;
		_dui = null;
	}

	public DigitalComponent_std(int n, DigitalComponentUI dui) {
		Pins = new Pin_std[n];
		NbPins = n;
		_dui = dui;
	}

	public boolean connectPin(int LocalPin, DigitalComponent c, int RemotePin, boolean InitialState) {
		if(LocalPin > NbPins)
			return false;
		else if(isPinConnected(LocalPin))
			return false;
		else {
			Pins[LocalPin - 1] = new Pin_std(c, RemotePin, InitialState);
			c.connectPin(RemotePin, this, LocalPin, InitialState);
			return true;
		}
	}

	public void setPinStateDontNotify(int p, boolean state) {
		Pins[p - 1].setStateDontNotify(state);
	}

	public void setPinState(int p, boolean state) {
		if(Pins[p - 1] != null)
			Pins[p - 1].setState(state);
	}

	protected boolean getPinState(int p) {
		if(Pins[p - 1] != null)
			return Pins[p - 1].getState();
		else
			return false;
	}

	public boolean isPinConnected(int p) {
		return (Pins[p - 1] == null) ? false : true;
	}

	public String getState() {
		return "Not implemented yet";
	}

	public void notifyOneCycle() {
	}

	public void refreshDisplay() {
		if(_dui == null)
			System.out.println(getState());
		else
			_dui.refresh(getState());
	}

	protected int readNumberOnPins(int first, int last) {
		int i, r = 0;

		for(i = first ; i <= last ; i++)
			r += (getPinState(i) ? Utils.Puiss2(i - first) : 0);

		return r;
	}

	protected void writeNumberOnPins(int first, int last, int num) {
		int i;

		for(i = first ; i <= last ; i++)
			if((num & Utils.Puiss2(i - first)) == 0)
				setPinState(i, false);
			else
				setPinState(i, true);
	}

	protected Pin Pins[];
	protected int NbPins;
	protected DigitalComponentUI _dui;
}