package info.bukova.isspst.services;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StringXmlMarshaller<T> {
	
	private final static Logger log = LoggerFactory.getLogger(StringXmlMarshaller.class);
	private final static String MARSHAL_ERROR = "Cannot marshal settings data: ";
	private final static String UNMARSHAL_ERROR = "Cannot unmarshal settings data: ";

	private Marshaller marshaller;
	private Unmarshaller unmarshaller;
	private Class<T> dataClass;
	
	public StringXmlMarshaller(Marshaller marshaller, Unmarshaller unmarshaller, Class<T> dataClass) {
		this.marshaller = marshaller;
		this.unmarshaller = unmarshaller;
		this.dataClass = dataClass;
	}
	
	public String marshalData(T data) {
		if (data == null) {
			return null;
		}
		
		StringWriter wr = new StringWriter();
		try {
			marshaller.setWriter(wr);
			marshaller. marshal(data);
		} catch (MarshalException e) {
			log.error(MARSHAL_ERROR + e.getMessage());
		} catch (ValidationException e) {
			log.error(MARSHAL_ERROR + e.getMessage());
		} catch (IOException e) {
			log.error(MARSHAL_ERROR + e.getMessage());
		}
		
		return wr.toString();
		
	}
	
	@SuppressWarnings("unchecked")
	public T unmarshalData(String data) {
		if (data == null) {
			return null;
		}
		
		StringReader sr = new StringReader(data);
		try {
			unmarshaller.setClass(dataClass);
			return (T) unmarshaller.unmarshal(sr);
		} catch (MarshalException e) {
			log.error(UNMARSHAL_ERROR + e.getMessage());
		} catch (ValidationException e) {
			log.error(UNMARSHAL_ERROR + e.getMessage());
		}
		
		return null;
	}

}
