package org.jcon.core.std;

import org.jcon.core.Cell;
import org.jcon.core.CellLifecycle;
import org.jcon.core.CellReplicator;
import org.jcon.core.CellServices;
import org.jcon.core.CellServicesUser;
import org.jcon.core.CellUser;
import org.jcon.core.Part;
import org.jcon.core.WorkerWrapper;
import org.jcon.core.std.PartStd;
import org.jcon.util.minor.KeyedVector;
import java.util.Enumeration;

/**
* This class is the standard Cell. For
* documentation see Cell for now. 
*
* @author Jack Harich
*/
public class CellStd extends PartStd implements Cell {

//---------- Protected Fields ----------------------------
protected KeyedVector parts = new KeyedVector();

// Core parts for massive delegation
protected CellLifecycle  lifecycle;
protected CellReplicator replicator;
protected CellServices   services;

//---------- Cell Implementation -------------------------
public void addPart(Part part) {
    // TODO Assertions on part name
    parts.addElement(part, part.getName());
    part.setParent(this);
    
    // Optional interfaces
    if (part.isContainer()) return;
    Object worker = ((WorkerWrapper)part).getWorker();

    if (worker instanceof CellUser) {
        ((CellUser)worker).setCell(this);
    }
    if (worker instanceof CellServicesUser) {
        ((CellServicesUser)worker).setCellServices(services);   
    }
}
public Part removePart(String partName) {
    Part part = (Part)parts.removeElement(partName);
    if (part != null) {
        part.setParent(null);
        // TODO Remove Cell and CellServices
    }
    return part;
}
public Part getPart(String partName) {
    return (Part)parts.getElementForKey(partName);
}
public Enumeration getParts() {
    return parts.elements();
}
public Object findWorker(String partName) {
    return services.findWorker(partName);
}
public void initCell() {
    // Get core part references
    
    // CellServices first, then we can use findWorker
    WorkerWrapper servicesWrapper = (WorkerWrapper)getPart("CellServices");
    services = (CellServices)servicesWrapper.getWorker();
    
    // CellReplicator
    replicator = (CellReplicator)services.findWorker("CellReplicator");
    
    // CellLifecycle
    lifecycle = (CellLifecycle)services.findWorker("CellLifecycle");
}
// TODO - This is not clean
//---------- StartablePart Implementation ----------------
public void startPart() {
    // These are now done elsewhere. Method is not needed
    //    or for possible future use.
    print(".startPart() - Does nothing");
    //if (! initialized) initialize();
    // ***lifecycle.startCell();
}
//----------- Replicable Implementation ------------------
public Object replicate() {
    return replicator.replicateCell(this);
}
//---------- Private Methods -----------------------------
//--- Std
private static void print(String text) {
    System.out.println("CellStd" + text);
}

} // End class