/*
 * Copyright 2006 Maskat Project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.maskat.xml.xmlbeans;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlCursor.TokenType;

public class EventSchemaUtil {

	static final String _xs = "http://www.w3.org/2001/XMLSchema";

	static final QName _xsiElement = new QName(_xs, "element", "xs");

	static final QName _name = new QName("name");

	public static List scanAllNodeName(InputStream eventDefSchema)
			throws XmlException, IOException {
		List result = new ArrayList();
		XmlObject xmlObj = XmlObject.Factory.parse(eventDefSchema);
		XmlCursor cursor = xmlObj.newCursor();
		loop: while (cursor.hasNextToken()) {
			TokenType type = cursor.toNextToken();
			switch (type.intValue()) {
			case XmlCursor.TokenType.INT_START:
				if (cursor.getName().equals(_xsiElement)) {
					processElement(cursor, result);
				}
				break;
			case XmlCursor.TokenType.INT_ENDDOC:
				break loop;
			}
		}

		return result;
	}

	private static void processElement(XmlCursor cursor, List result) {

		loop: while (cursor.hasNextToken()) {
			TokenType type = cursor.toNextToken();
			switch (type.intValue()) {
			case XmlCursor.TokenType.INT_ATTR:
				if (cursor.getName().equals(_name)) {
					result.add(cursor.getTextValue());
					break loop;
				}
				break;
			case XmlCursor.TokenType.INT_START:
				break loop;
			case XmlCursor.TokenType.INT_ENDDOC:
				break loop;
			}
		}

	}
}
