/*
 * 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.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

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.GroupPatternCategory;
import xmltorng.i2s.framework.AttributesPatternCategory;
import xmltorng.i2s.util.PatternFactory;
import xmltorng.i2s.impl.AttributesPatternCategoryImpl;

/**
 * An interleave pattern category is a pattern category for interleave patterns
 *   whose child patterns are repeatable or not repeatable,
 *   optional or required refs.
 * 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>
 * zerorOrMoreElement ::= element
 *   | (<optional> element </optional>)
 *   | (<oneOrMore> element </oneOrMore>)
 *   | (<optional><oneOrMore> element </oneOrMore></optional>)
 *   | (<oneOrMore><optional> element </optional></oneOrMore>)
 * interleave ::= zeroOrMoreElement
 *   | (<interleave> zerorOrMoreElement+ </interleave>)
 * elementsAndText ::= interleave
 *   | (<interleave> interleave <text/> </interleave>)
 * content ::= elementsAndText | (<group> attributes elementsAndText </group>)
 *
 * Additional constraint : an element with a given name may appear at most in
 *   one child pattern.
 */
public final class InterleavePatternCategoryImpl implements PatternCategory {
  private static final boolean DEBUG = false;
  private AttributesPatternCategory attributesPatternCategory;
  private boolean hasText = false;
  private int patternCount = 0;
  private final Map fromNameToElementUsage = new HashMap();

  static private final class ElementUsage {
    public boolean isRepeatable = false;
    public int usageCount = 0;
      // The element is optional if and only if usageCount < patternCount.
  }

  public InterleavePatternCategoryImpl() {
    this.attributesPatternCategory = new AttributesPatternCategoryImpl();
  }

  public InterleavePatternCategoryImpl(
      AttributesPatternCategory attributesPatternCategory, boolean hasText) {
    this.attributesPatternCategory = attributesPatternCategory;
    this.hasText = hasText;
  }

  public InterleavePatternCategoryImpl(
      ChoicePatternCategory patternCategory,
      AttributesPatternCategory attributesPatternCategory, boolean hasText) {
    Map fromElementNameToRepeatable =
        patternCategory.fromElementNameToRepeatable();
    this.patternCount = 1;
    int usageCount = patternCategory.isPatternOptional() ? 0 : 1;
    Iterator iterator = fromElementNameToRepeatable.keySet().iterator();
    while (iterator.hasNext()) {
      Name elementName = (Name)iterator.next();
      ElementUsage elementUsage = new ElementUsage();
      this.fromNameToElementUsage.put(elementName, elementUsage);
      elementUsage.isRepeatable = ((Boolean)fromElementNameToRepeatable.
                                   get(elementName)).booleanValue();
      elementUsage.usageCount = usageCount;
    }
    this.attributesPatternCategory = attributesPatternCategory;
    this.hasText = hasText;
  }

  public InterleavePatternCategoryImpl(
      GroupPatternCategory patternCategory,
      AttributesPatternCategory attributesPatternCategory, boolean hasText) {
    this.patternCount = 1;
    Iterator iterator = patternCategory.elementNameSet().iterator();
    while (iterator.hasNext()) {
      Name elementName = (Name)iterator.next();
      ElementUsage elementUsage = new ElementUsage();
      elementUsage.isRepeatable = patternCategory.isRepeatable(elementName);
      elementUsage.usageCount = patternCategory.isOptional(elementName) ? 0 : 1;
      this.fromNameToElementUsage.put(elementName, elementUsage);
    }
    this.attributesPatternCategory = attributesPatternCategory;
    this.hasText = hasText;
  }

  public AttributesPatternCategory attributesPatternCategory() {
    return attributesPatternCategory;
  }

  public boolean hasText() {
    return hasText;
  }

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

  public Pattern fullPattern(Map fromNameToElementDefinition) {
    if (this.fromNameToElementUsage.size() == 0)
      return null;
    List patternList = new ArrayList();
    Iterator iterator = this.fromNameToElementUsage.keySet().iterator();
    if (DEBUG)
      System.out.print('(');
    boolean isStarted = false;
    while (iterator.hasNext()) {
      Name elementName = (Name)iterator.next();
      ElementUsage elementUsage =
          (ElementUsage)this.fromNameToElementUsage.get(elementName);
      NonEmptyPattern childPattern = PatternFactory.namedElement(
          fromNameToElementDefinition, elementName, elementUsage.isRepeatable);
      if (elementUsage.usageCount < this.patternCount)
        childPattern =
        PatternFactory.choice(new NonEmptyPattern[] {childPattern}, true);
      patternList.add(childPattern);
      if (DEBUG) {
        if (isStarted)
          System.out.print(" & ");
        else
          isStarted = true;
        System.out.print(elementName.getName());
        char ch = ' ';
        if (elementUsage.isRepeatable)
          if (elementUsage.usageCount < this.patternCount)
            ch = '*';
          else
            ch = '+';
        else
          if (elementUsage.usageCount < this.patternCount)
            ch = '?';
        if (ch != ' ')
          System.out.print(ch);
      }
    }
    if (DEBUG)
      System.out.println(')');
    NonEmptyPattern[] patterns = new NonEmptyPattern[patternList.size()];
    patternList.toArray(patterns);
    NonEmptyPattern pattern = PatternFactory.interleave(patterns);
    if (this.hasText)
      pattern = PatternFactory.interleave(
          new NonEmptyPattern[] {pattern, PatternFactory.textPattern()});
    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) {
    Set nameSet = new HashSet();
    for (int k = 0; k < repeatableElementNames.length; k++) {
      RepeatableName repeatableElementName = repeatableElementNames[k];
      Name elementName = repeatableElementName.getName();
      ElementUsage elementUsage =
          (ElementUsage)this.fromNameToElementUsage.get(elementName);
      if (elementUsage == null) {
        elementUsage = new ElementUsage();
        this.fromNameToElementUsage.put(elementName, elementUsage);
      }
      elementUsage.usageCount++;
      if (repeatableElementName.isRepeatable() || nameSet.contains(elementName))
        elementUsage.isRepeatable = true;
      nameSet.add(elementName);
    }
    this.patternCount++;
    if (hasText)
      this.hasText = true;
    this.attributesPatternCategory.addAttributeNames(attributeNames);
    return true;
  }
}
