package org.jcon.core.std;

import org.jcon.core.Cell;
import org.jcon.core.CellUser;
import org.jcon.core.CellServices;
import org.jcon.core.Part;
import org.jcon.core.WorkerWrapper;
import org.jcon.core.std.PartStd;
import java.util.Enumeration;

/**
* This class is the standard CellServices. For
* documentation see CellServices for now. 
* It is not a service part.
*
* @author Jack Harich
*/
public class CellServicesStd extends PartStd implements CellServices {

//---------- Protected Fields ----------------------------
protected Cell cell;

//---------- CellServices Implementation -----------------
public Part findPart(String partName) {
    Part part = getPart(partName);
    
    // Case 1 - Found in this container
    if (part != null) return part;
    
    // Search upward until root encountered
    Cell upwardCell = cell.getParent();
    while (upwardCell != null) {
        part = upwardCell.getPart(partName);
        upwardCell = upwardCell.getParent();
    }
    // Case 2 - Never found upwardly
    if (part == null) {
        throw new IllegalStateException("Part '" + partName +
        "' not found in this container or above.");
    }
    // Case 3 - Found upwardly, is service part
    if (part.isService()) {
        return part;
    }
    // Case 4 - Found upwardly, not service part
    throw new IllegalStateException("Part '" + partName +
    "' found upwardly but is not a service part.");
}
public Object findWorker(String partName) {
    return ((WorkerWrapper)findPart(partName)).getWorker();
}
public Part getPart(String partName) {
    return cell.getPart(partName);
}
public Object getWorker(String partName) {
    return ((WorkerWrapper)cell.getPart(partName)).getWorker();
}
public Enumeration getParts() {
    return cell.getParts();
}
//----------- Replicable Implementation ------------------
/**
* Note this needs setCell(Cell) called to be complete.
*/
public Object replicate() {
    return new CellServicesStd();
}
//----------- CellUser Implementation --------------------
public void setCell(Cell cell) {
    this.cell = cell;
}
public void releaseCell() {
    cell = null;
}
//---------- Private Methods -----------------------------
//--- Std
private static void print(String text) {
    System.out.println("CellServicesStd" + text);
}

} // End class