/*------------------------------------------------------------------------------------
Copyright (c)2000 TogetherSoft Corporation. Patents pending. All rights reserved. 
------------------------------------------------------------------------------------*/ 

package com.togethersoft.modules.xmleditor.xmltree;

import java.util.*;
import com.togethersoft.modules.xmleditor.dtd.*;

public class ElementInstHolder extends InstHolder
{
  private DTDElementItemDef m_elementItemDef;

  //--------------------------------------------------------------------
  public ElementInstHolder (DTDElementItemDef elementItemDef)
  {
    super (elementItemDef);
    m_elementItemDef = elementItemDef;
  }

  //--------------------------------------------------------------------
  public boolean isComplete()
  {
    // check completeness by cardinality
    switch (m_elementItemDef.getCardinality())
    {
      case DTDItemDef.CARDINALITY_ONCE:
      case DTDItemDef.CARDINALITY_ONCE_OR_MORE:

        if (m_instances.size() == 0)
          return false;
    }

    return super.isComplete();
  }

  //--------------------------------------------------------------------
  public int checkElementInstAllowance (DTDElementDef elementDef)
  {
    if (elementDef != m_elementItemDef.getElementDef())
      return ElementInst.NEA_PROHIBITED;

    int allowance = ElementInst.NEA_PROHIBITED;
    
    switch (m_elementItemDef.getCardinality())
    {
      case DTDItemDef.CARDINALITY_ONCE:
        allowance = (m_instances.size() == 0) ?
                    ElementInst.NEA_REQUIRED : ElementInst.NEA_PROHIBITED;
        break;

      case DTDItemDef.CARDINALITY_ONCE_OR_NEVER:
        allowance = (m_instances.size() == 0) ?
                    ElementInst.NEA_ALLOWED : ElementInst.NEA_PROHIBITED;
        break;

      case DTDItemDef.CARDINALITY_ONCE_OR_MORE:
        allowance = (m_instances.size() == 0) ?
                    ElementInst.NEA_REQUIRED : ElementInst.NEA_ALLOWED;
        break;

      case DTDItemDef.CARDINALITY_ANY_TIMES:
        allowance = ElementInst.NEA_ALLOWED;
        break;
    }

    return allowance;
  }

  //--------------------------------------------------------------------
  public boolean putElementInst (ElementInst elementInst)
  {
    if (checkElementInstAllowance (elementInst.getElementDef()) == ElementInst.NEA_PROHIBITED)
      return false;

    m_instances.addElement (elementInst);
    return true;
  }

  //--------------------------------------------------------------------
  public boolean deleteElementInst (ElementInst elementInst)
  {
    return m_instances.removeElement (elementInst);
  }

  //--------------------------------------------------------------------
  public Vector getContainedElements()
  {
    return m_instances;
  }

}
