/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2001 The Apache Software Foundation.  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 software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * 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 APACHE SOFTWARE FOUNDATION 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.apache.org.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.xerces.impl.v2;

import java.util.Vector;

/**
 * To store and validate information about substitutionGroup
 *
 * @author Sandy Gao, IBM
 * @author Rahul Srivastava, Sun Microsystems Inc.
 *
 * @version $Id: SubstitutionGroupHandler.java,v 1.3 2001/09/19 16:25:35 sandygao Exp $
 */
public class SubstitutionGroupHandler {

    // grammar resolver
    private XSGrammarResolver fGrammarResolver;

    // Substitution group registry
    private Vector fSubstitutionGroup;

    /**
     * Default constructor
     *
     * @param grammarResolver
     */
    SubstitutionGroupHandler(XSGrammarResolver grammarResolver) {
        fGrammarResolver = grammarResolver;
        fSubstitutionGroup = new Vector(10,5);
    }

    /**
     * clear the internal registry of substitutionGroup information
     */
    public void reset() {
        fSubstitutionGroup.clear();
    }

    /**
     * add one substitution group pair
     *
     * @param element
     */
    public void addSubstitutionGroup(XSElementDecl element) {
    	//REVISIT: Do we need this check here!
    	if (element.fSubGroup != null) {
        	fSubstitutionGroup.addElement(element);
        }
    }

    /**
     * @param  element
     * @return all elements that substitute the given element, directly or 
     *         transitively including the element itself.
     */
    public XSElementDecl[] getSubstitutionGroup(XSElementDecl element) {
    	return getSubstitutionGroup(element.fTargetNamespace, element.fName);
    }

    /**
     * get all elements that can substitute the given element,
     * according to the spec, we shouldn't consider the {block} constraints.
     *
     * @param  elementUri
     * @param  elementName
     * @return all elements that substitute the given element, directly or 
     *         transitively including the element itself.
     */
    public XSElementDecl[] getSubstitutionGroup(String elementUri, String elementName) {
        Vector tempSubstitutionGroups = new Vector(5,5);
        XSElementDecl headElement = null;
        XSElementDecl element = null;
        
        SchemaGrammar grammar = fGrammarResolver.getGrammar(elementUri);
        element = grammar.getGlobalElementDecl(elementName);
        tempSubstitutionGroups.addElement(element);
        
        // Iterate thru head elements, initially one viz. the element itself
        for (int i=0, k=0; i<tempSubstitutionGroups.size(); i++) {
        	headElement = (XSElementDecl)tempSubstitutionGroups.elementAt(i);
        	if ( (headElement.fBlock & SchemaSymbols.SUBSTITUTION) != 0 )
        		continue;
        	
        	// Iterate thru substitution group registry
        	// Each iteration, bubbles out the head elment found, if any.
        	for (int j=k, size=fSubstitutionGroup.size(); j<size; j++) {
        		element = (XSElementDecl)fSubstitutionGroup.elementAt(j);
        		// If a element substitutes a head element AND is not the 
        		// element from where we started finding substitutions
        		// implies not a circular reference.
        		if ( (element.fSubGroup.fTargetNamespace == headElement.fTargetNamespace) && 
        		     (element.fSubGroup.fName == headElement.fName) && 
        		     (element.fName != elementName) ) {
        			tempSubstitutionGroups.addElement(element);
        			// swap j,k
        			fSubstitutionGroup.setElementAt(fSubstitutionGroup.elementAt(k),j);
        			fSubstitutionGroup.setElementAt(element,k);
        			k++;
        		}
        	}
        }
        
        // copy elements from vector to array
        int size = tempSubstitutionGroups.size();
        XSElementDecl[] elements = new XSElementDecl[size];
        tempSubstitutionGroups.copyInto(elements);
        
        return elements;
    }

    /**
     * check whether an element with the given type can have the other element
     * as its {substitution group affiliation}.
     *
     * @param element
     */
    public static boolean checkSubstitutionGroupOK(XSElementDecl element) {

        XSElementDecl headElement = element.fSubGroup;
        
	// if block attr. of head element is #all or substitution then, no substitution allowed.
	if (headElement.fBlock != SchemaSymbols.EMPTY_SET)
		if ((headElement.fBlock & SchemaSymbols.SUBSTITUTION) != 0)
			return false;
	
        // type should be same or derived from head element's type.
        XSTypeDecl headType = headElement.fType;
        XSTypeDecl subType = element.fType;

        //REVISIT: uncomment the following when XSTypeDecl is finalized to a class
        //return XSConstraints.checkTypeDerivationOk(subType, headType, headType.getFinalSet());
        
        return true;
    }

} // class SubstitutionGroupHandler
