package jetbrains.mps.smodel.persistence.def.v4;

/*Generated by MPS */

import jetbrains.mps.annotations.GeneratedClass;
import jetbrains.mps.smodel.persistence.def.VisibleModelElements;
import java.util.Map;
import org.jetbrains.mps.openapi.model.SModelReference;
import java.util.HashMap;
import org.jdom.Element;
import java.util.List;
import jetbrains.mps.vcspersistence.VCSPersistenceSupport;
import jetbrains.mps.vcspersistence.VCSPersistenceUtil;

@GeneratedClass(node = "r:8276e029-a527-420e-8e0f-72df2934554c(jetbrains.mps.smodel.persistence.def.v4)/453110257780703303", model = "r:8276e029-a527-420e-8e0f-72df2934554c(jetbrains.mps.smodel.persistence.def.v4)")
/*package*/ class DOMVisibleModelElements implements VisibleModelElements {
  private Map<Integer, SModelReference> myVisibleModelElements = new HashMap<Integer, SModelReference>();
  private int myMaxVisibleModelIndex = 1;
  private Element myModelElement;
  /*package*/ DOMVisibleModelElements(Element modelElement) {
    myModelElement = modelElement;
    parseVisibleElements();
  }
  private void parseVisibleElements() {
    List visibles = myModelElement.getChildren(VCSPersistenceSupport.VISIBLE_ELEMENT);
    for (Object aVisible : visibles) {
      Element element = (Element) aVisible;
      String indexValue = element.getAttributeValue(VCSPersistenceSupport.MODEL_IMPORT_INDEX);
      int index = Integer.parseInt(indexValue);
      String visibleModelUIDString = element.getAttributeValue(VCSPersistenceSupport.MODEL_UID);
      myVisibleModelElements.put(index, VCSPersistenceUtil.createModelReference(visibleModelUIDString));
      myMaxVisibleModelIndex = Math.max(index, myMaxVisibleModelIndex);
    }
  }
  @Override
  public int getVisibleModelIndex(SModelReference modelReference) {
    for (Map.Entry<Integer, SModelReference> entry : myVisibleModelElements.entrySet()) {
      if (modelReference.equals(entry.getValue())) {
        return entry.getKey();
      }
    }
    return addModel(modelReference);
  }
  private int addModel(SModelReference modelReference) {
    myMaxVisibleModelIndex++;
    myVisibleModelElements.put(myMaxVisibleModelIndex, modelReference);
    Element visibleElement = new Element(VCSPersistenceSupport.VISIBLE_ELEMENT);
    visibleElement.setAttribute(VCSPersistenceSupport.MODEL_IMPORT_INDEX, myMaxVisibleModelIndex + "");
    visibleElement.setAttribute(VCSPersistenceSupport.MODEL_UID, modelReference.toString());
    myModelElement.addContent(visibleElement);
    return myMaxVisibleModelIndex;
  }
  @Override
  public SModelReference getModelUID(int index) {
    return myVisibleModelElements.get(index);
  }
}
