package javaflow.network.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import javaflow.components.api.InputPort;
import javaflow.components.api.InputPorts;
import javaflow.network.api.NetworkComponent;
import javaflow.network.api.PortReference;
final class InputPortsImpl<T> implements InputPorts<T>, Port {
private AbstractRunnableComponent owner;
private final ArrayList<InputPortImpl> inports = new ArrayList<>();
private final String componentName;
private final String portBaseName;
InputPortsImpl(PortReference portDef) {
this.componentName = portDef.componentName();
this.portBaseName = portDef.portName();
}
@Override
public int size() {
return inports.size();
}
@Override
public void closeAll() {
for (InputPortImpl port : inports) {
port.close();
}
}
@Override
public Iterator<InputPort<T>> iterator() {
return (Iterator) Collections.unmodifiableCollection(inports).iterator();
}
@Override
public void close() {
closeAll();
}
@Override
public int getOpenPortCount() {
int sum = 0;
for (InputPortImpl in : inports) {
sum += in.getOpenPortCount();
}
return sum;
}
@Override
public boolean hasPacket() {
for (InputPortImpl in : inports) {
if (in.hasPacket()) {
return true;
}
}
return false;
}
@Override
public void setOwner(AbstractRunnableComponent owner) {
for (Port port : inports) {
port.setOwner(owner);
}
this.owner = owner;
}
InputPortImpl get(int i) {
while (i >= inports.size()) {
int index = inports.size();
InputPortImpl in = new InputPortImpl(new PortReference(componentName, portBaseName, index));
inports.add(in);
owner.inputPortOpened();
in.setOwner(owner);
}
return inports.get(i);
}
@Override
public InputPortImpl port(int index) {
return inports.get(index);
}
@Override
public String toString() {
return toString(0);
}
@Override
public String toString(int indentation) {
StringBuilder builder = new StringBuilder();
builder.append(Utils.indent(indentation, componentName));
builder.append(".");
builder.append(portBaseName);
builder.append("[]:\n");
for (int i = 0; i < size(); i++) {
InputPortImpl port = port(i);
builder.append(Utils.indent(indentation, " #"));
builder.append(i);
builder.append(": ");
builder.append(port.queueSize());
builder.append(" messages waiting,");
if (port.hasBeenClosed()) {
builder.append(" port has been closed");
} else {
builder.append(" port is open. Connected from " + port.connected);
}
builder.append("\n");
}
return builder.toString();
}
@Override
public NetworkComponent getOwner() {
return owner;
}
@Override
public void reopen() {
for(InputPortImpl in : inports){
in.reopen();
}
}
}