/*
 * Created on 24.06.2004
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *  
 */
package networkconsole.datamodel.sax;

import java.io.IOException;
import java.util.Iterator;

import networkconsole.datamodel.JdbcEntry;
import networkconsole.datamodel.JdbcEntryList;

import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.XMLFilterImpl;

/**
 * @author Eugene Prokopiev <eugene_prokopiev@mail.ru>
 * 
 */
public class JdbcEntryListXMLReader extends XMLFilterImpl {
	
	public void parse(InputSource input) throws SAXException, IOException {
		
		if (!(input instanceof JdbcEntryListInputSource))
			super.parse(input);
		
		JdbcEntryList list = ((JdbcEntryListInputSource)input).getList();
		String name = ((JdbcEntryListInputSource)input).getName();
		
		AttributesImpl emptyAttrs = new AttributesImpl();
		AttributesImpl nameAttrs = new AttributesImpl();
		nameAttrs.addAttribute("", "name", "name", "", name);
			
		ContentHandler handler = getContentHandler();
		handler.startDocument();
		handler.startElement("", "table", "table", nameAttrs);
		
		if (list.getFieldNames() != null) {
		
			handler.startElement("", "columns", "columns", emptyAttrs);		
			Iterator fieldsIterator = list.getFieldNames().iterator();
			while (fieldsIterator.hasNext()) {			
				String columnName = fieldsIterator.next().toString();
				handler.startElement("", "column", "column", emptyAttrs);
				handler.characters(columnName.toCharArray(), 0, columnName.length());
				handler.endElement("", "column", "column");
			}
			handler.endElement("", "columns", "columns");		
			
			handler.startElement("", "rows", "rows", emptyAttrs);
			Iterator entriesIterator = list.getEntries().iterator();
			while (entriesIterator.hasNext()) {			
				handler.startElement("", "row", "row", emptyAttrs);
				JdbcEntry entry = (JdbcEntry)entriesIterator.next();	
				for (int i = 0; i < entry.size(); i++) {
					handler.startElement("", "field", "field", emptyAttrs);
					String field = entry.getField(i);
					handler.characters(field.toCharArray(), 0, field.length());
					handler.endElement("", "field", "field");
				}			
				handler.endElement("", "row", "row");				
			}
			handler.endElement("", "rows", "rows");
		}
		
		handler.endElement("", "table", "table");
		handler.endDocument();
	}
}
