package eu.nets.sis.idrights.demoapp.util;

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

import javax.xml.bind.JAXBException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.xml.serialize.Method;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import no.bbs.trust.b2b.xmlapi.message.Marshaller;
import no.bbs.trust.b2b.xmlapi.message.domain.B2BMessage;

/**
 * Utility class for ID-Rights
 *
 */
public class IDRightsUtil {
	
	private static Logger logger = LogManager.getLogger(IDRightsUtil.class);
	
	/**
	 * This method converts B2BMessage object to String, to display it in result page.
	 * @param response B2BMessage object, which contains result of requested id-rights message
	 * @return response of the B2BMessage in XML string format
	 */
	public static String convertB2BMsgToString(B2BMessage response) {
		String xmlResponse = null;
		try {
			xmlResponse = Marshaller.instance.marshall(response);
		} catch (JAXBException e) {
			logger.error("Error while converting B2Bobject to XML.", e);
		}
		return xmlResponse;
	}
	
	/**
	 * This method converts XML string into String in readble format.
	 * @param xml XML in String
	 * @return String in readble format
	 */
	public static String convertToXMLStringFormat(String xml) {
		Document doc = null;
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);
			dbf.setValidating(false);
			dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(new InputSource(new StringReader(xml)));
		} catch (Exception e) {
			logger.error("Error while converting String in XML format.", e);
		}
		return document2String(doc);
	}
	
	/**
	 * This method converts Document into String format.
	 * @param doc Document object
	 * @return String
	 */
	private static String document2String(Document doc) {
		String result = null;
		if (null == doc) {
			logger.error("Parser error while converting String to Document object.");
			return result;
		}
		
		StringWriter writer = new StringWriter();
		
		try {
			OutputFormat outputFormat = new OutputFormat(Method.XML, "UTF-8", true);
			outputFormat.setOmitXMLDeclaration(true);
			XMLSerializer serializer = new XMLSerializer(writer, outputFormat);
			serializer.serialize(doc);
			result = writer.toString();
		} catch (Exception e) {
			logger.error("Error while converting Document to String.", e);
		} finally {
			if (null != writer) {
				try {
					writer.close();
				} catch (IOException e) {
					// Nothing to do
				}
			}
		}
		return result;
	}

}
