/*
 * 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;

import java.io.Writer;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

public abstract class DefXmlSerializer {
	protected Object def;

	protected Writer writer;

	private int indentSpace = 3;

	protected DefXmlSerializer(Object def, Writer writer) {
		this.def = def;
		this.writer = writer;
	}

	public void write() throws XMLStreamException {
		XMLOutputFactory factory = XMLOutputFactory.newInstance();
		XMLStreamWriter writer = factory.createXMLStreamWriter(this.writer);
		writer.writeStartDocument("UTF-8", "1.0");
		writer.writeCharacters("\n");
		customizeWrite(writer);

		writeObj(writer, def, 0);

		writer.writeEndDocument();
		writer.flush();
		writer.close();
	}

	abstract protected void customizeWrite(XMLStreamWriter writer)
			throws XMLStreamException;

	public int getIndentSpace() {
		return indentSpace;
	}

	public void setIndentSpace(int indentSpace) {
		this.indentSpace = indentSpace;
	}

	protected abstract void writeObj(XMLStreamWriter writer, Object def,
			int hierarchyLvl) throws XMLStreamException;

	protected abstract String getElementName(Object def);

	protected abstract void writeDefAttribute(XMLStreamWriter writer, Object def)
			throws XMLStreamException;

	protected void writeIndent(XMLStreamWriter writer, int hierarchyLvl)
			throws XMLStreamException {
		for (int i = 0; i < hierarchyLvl * indentSpace; i++) {
			writer.writeCharacters(" ");
		}
	}

	protected static void writeOneAttribute(XMLStreamWriter writer,
			String name, String value) throws XMLStreamException {
		if (value == null)
			return;
		writer.writeAttribute(name, value);

	}
}
