/*
 * The_xmloperator_project Software License, Version 1.7
 *
 * Copyright (c) 2000 - 2003 The_xmloperator_project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *      "This product includes or uses software developped
 *       by The_xmloperator_project (http://www.xmloperator.net/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. Products derived from this software may not be called "xmloperator",
 *    nor may "xmloperator" appear in their name, without prior written
 *    permission. For written permission, please contact
 *    the xmloperator project administrator.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE_XMLOPERATOR_PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * Further information can be found on the project's site
 * (http://www.xmloperator.net/).
 */
package xmltorng.i2s.impl;

import java.util.Iterator;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;

import xmltorng.framework.document.relaxng.Name;
import xmltorng.framework.document.relaxng.Pattern;
import xmltorng.framework.document.relaxng.NonEmptyPattern;
import xmltorng.i2s.framework.RepeatableName;
import xmltorng.i2s.framework.PatternCategory;
import xmltorng.i2s.framework.ChoicePatternCategory;
import xmltorng.i2s.framework.AttributesPatternCategory;
import xmltorng.i2s.util.PatternFactory;
import xmltorng.i2s.impl.AttributesPatternCategoryImpl;

/**
 * The <code>RepeatableElementPatterncategory</code> is a pattern category
 *   that contains choice patterns between repeatable or not repeatable named
 *   elements.
 * May also contain attributes and/or text.
 *
 * Formally:
 * attribute ::= <attribute name="QName"> <text/> </attribute>
 * attributes ::= attribute | (<group> attribute+ </group>)
 * element ::= <element name="QName"> any </element>
 * oneOrMoreElement ::= element | (<oneOrMore> element </oneOrMore>)
 *   | (<choice> (element* & (<oneOrMore> element </oneOrMore>)+) </choice>)
 * oneOrMoreElementAndText ::= oneOrMoreElement
 *   | (<interleave> oneOrMoreElement <text/> </interleave>)
 * content ::= oneOrMoreElementAndText
 *   | (<group> attributes oneOrMoreElementAndText </group>)
 */
public class RepeatableElementPatternCategory
    implements ChoicePatternCategory {
  protected AttributesPatternCategory attributesPatternCategory = null;
  protected boolean hasText = false;
  protected final Map fromElementNameToRepeatable = new HashMap();

  protected RepeatableElementPatternCategory() {
    attributesPatternCategory = new AttributesPatternCategoryImpl();
  }

  protected RepeatableElementPatternCategory(
      AttributesPatternCategory attributesPatternCategory, boolean hasText) {
    this.attributesPatternCategory = attributesPatternCategory;
    this.hasText = hasText;
  }

  protected RepeatableElementPatternCategory(
      Name elementName, boolean isRepeatable) {
    this.fromElementNameToRepeatable.put(
        elementName, isRepeatable ? Boolean.TRUE : Boolean.FALSE);
  }

  public void addElementName(Name elementName, boolean isRepeatable) {
    if (!isRepeatable) {
      Boolean isThisRepeatable =
          (Boolean)this.fromElementNameToRepeatable.get(elementName);
      if (isThisRepeatable != null)
        isRepeatable = isThisRepeatable.booleanValue();
    }
    this.fromElementNameToRepeatable.put(
        elementName, isRepeatable ? Boolean.TRUE : Boolean.FALSE);
  }

  public AttributesPatternCategory attributesPatternCategory() {
    return attributesPatternCategory;
  }

  public boolean hasText() {
    return hasText;
  }

  /////////////////////
  // Object overloading
  /////////////////////

  public String toString() {
    StringBuffer sb = new StringBuffer();
    sb.append('(');
    Iterator iterator = this.fromElementNameToRepeatable.keySet().iterator();
    boolean isStarted = false;
    while (iterator.hasNext()) {
      if (isStarted)
        sb.append('|');
      else
        isStarted = true;
      Name name = (Name)iterator.next();
      sb.append(name.getName());
      if (((Boolean)this.fromElementNameToRepeatable.get(name)).booleanValue())
        sb.append('+');
    }
    sb.append(')');
    return sb.toString();
  }

  /////////////////////////////////
  // PatternCategory implementation
  /////////////////////////////////

  public Pattern fullPattern(Map fromNameToElementDefinition) {
    int elementNameCount = fromElementNameToRepeatable.size();
    if (elementNameCount == 0)
      return null;
    NonEmptyPattern pattern;
    if (elementNameCount == 1) {
      Name name = (Name)fromElementNameToRepeatable.keySet().iterator().next();
      boolean isRepeatable =
          ((Boolean)fromElementNameToRepeatable.get(name)).booleanValue();
      pattern = PatternFactory.namedElement(
          fromNameToElementDefinition, name, isRepeatable);
    }
    else
     pattern = PatternFactory.choiceFromRepeatableNames(
        fromNameToElementDefinition, fromElementNameToRepeatable);
    if (this.hasText)
      pattern = PatternFactory.interleave(
          new NonEmptyPattern[] {pattern, PatternFactory.textPattern()});
    if (this.attributesPatternCategory == null)
      return pattern;
    Pattern attributesPattern = this.attributesPatternCategory.fullPattern();
    return attributesPattern.isEmpty() ? pattern :
        PatternFactory.group(
        new NonEmptyPattern[] {(NonEmptyPattern)attributesPattern, pattern});
  }

  public boolean addPattern(
      Name[] attributeNames, boolean hasText,
      RepeatableName[] repeatableElementNames) {
    if (repeatableElementNames.length != 1)
     return false;
   RepeatableName repeatableElementName = repeatableElementNames[0];
   this.addElementName(repeatableElementName.getName(),
                repeatableElementName.isRepeatable());
   if (hasText)
     this.hasText = true;
   this.attributesPatternCategory.addAttributeNames(attributeNames);
   return true;
  }

  ///////////////////////////////////////
  // ChoicePatternCategory implementation
  ///////////////////////////////////////

  public Map fromElementNameToRepeatable() {
    return Collections.unmodifiableMap(this.fromElementNameToRepeatable);
  }

  public boolean isPatternOptional() {
    return false;
  }
}
