package eu.dnetlib.common.utils;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.namespace.QName;


public class XMLSerializer<T> {

	private Marshaller marshaller;
	private Class<T> clazz;
	
	public XMLSerializer(Class<T> clazz){
		this.clazz = clazz;
		try {
			init();
		} catch (JAXBException e) {
			throw new IllegalArgumentException(e);
		}
	}
	

	protected void init() throws JAXBException{
		Class<?>[] all = {this.clazz};
		JAXBContext context = JAXBContext.newInstance(all);
		marshaller = context.createMarshaller();
		marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", false);		
	}
	
	public String getAsXml(T record) throws JAXBException{
		final StringWriter buffer = new StringWriter();
		marshaller.marshal(createElement(record), buffer);
		return buffer.toString();
	}

	protected JAXBElement<T> createElement(final T value) {
		final XmlRootElement annotation = this.clazz.getAnnotation(XmlRootElement.class); 
		return new JAXBElement<T>(new QName(annotation.namespace(), annotation.name()), this.clazz, null, value);
	}
}
