/*
 * Copyright (c) 2006-2008 Maskat Project.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Maskat Project - initial API and implementation
 */
package org.maskat.core.betwixt;

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

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.apache.commons.betwixt.io.BeanWriter;
import org.apache.commons.betwixt.io.WriteContext;
import org.apache.commons.betwixt.strategy.NamespacePrefixMapper;


public class MaskatBeanWriter extends BeanWriter {
	
	public MaskatBeanWriter() {
		super();
		this.setXMLIntrospector(new MaskatXMLIntrospector());
	}
	
	public MaskatBeanWriter(Writer writer) {
		super(writer);
		this.setXMLIntrospector(new MaskatXMLIntrospector());
	}
	
	/**
	 * a way to don't write the <children></children> of DynaBean 
	 */
	protected void startElement(
            WriteContext context,
            String uri, 
            String localName, 
            String qualifiedName, 
            Attributes attr)
                throws
                    IOException,
                    SAXException {
		if ("children".equals(qualifiedName) && attr.getLength() <= 0) {
			return;
		}
		if ("layoutDef".equals(qualifiedName)) {
			NamespacePrefixMapper mapper = this.getXMLIntrospector().
				getConfiguration().getPrefixMapper();
						
			Map prefixMap = ((MaskatNamespacePrefixMapper) mapper).getPrefixes();
			AttributesImpl attribute = new AttributesImpl();
			for (Iterator ite = prefixMap.keySet().iterator(); ite.hasNext();) {
	        	String key = (String) ite.next();
	        	attribute.addAttribute("", "", "xmlns:" + key, "NOTATION", (String) prefixMap.get(key));
	        }
	        attr = attribute;
		}

		super.startElement(context, uri, localName, qualifiedName, attr);
	}
	
	/**
	 * a way to don't write the <children></children> of DynaBean 
	 */
	protected void endElement(
            WriteContext context,
            String uri, 
            String localName, 
            String qualifiedName)
                throws
                    IOException,
                    SAXException {
		if ("children".equals(qualifiedName)) {
			return;
		}
		super.endElement(context, uri, localName, qualifiedName);
	}
}
