package net.aocat.siri.proxy.client.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;

public class Utils {
	
	/**
	 * Prints an XMLObject.
	 * @param str String to convert to XmlObject to print
	 * @throws XmlException 
	 */
	public static void printXmlObject(String str) throws XmlException{
		XmlObject xmlObj = XmlObject.Factory.parse(str);
		//print request message
		XmlOptions xmlOptions = new XmlOptions();
		xmlOptions.setSavePrettyPrint();
		xmlOptions.setSaveOuter();
		System.out.println(xmlObj);
	}
	
	/**
	 * Prints an XMLObject.
	 * @param xmlObj XMLObject to print
	 */
	public static void printXmlObject(XmlObject xmlObj){
		//print request message
		XmlOptions xmlOptions = new XmlOptions();
		xmlOptions.setSavePrettyPrint();
		xmlOptions.setSaveOuter();
		System.out.println(xmlObj);
	}
	
	
	/**
	 * Prints an XMLObject.
	 * @param xmlObj XMLObject to print
	 */
	public static void printXmlObject(XmlObject xmlObj, String filePath){
		
		//print request message
		XmlOptions xmlOptions = new XmlOptions();
		xmlOptions.setSavePrettyPrint();
		xmlOptions.setSaveOuter();
		System.out.println(xmlObj);
		
		//save to file
		if(filePath!=null){
			try{
				File file = new File(filePath);
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(xmlObj.getDomNode().getTextContent().getBytes());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static byte[] getBytesFromFile(String path) throws Exception {
		byte[] bytes = null;
		FileInputStream is = null;
		
		try {
			is = new FileInputStream(new File(path));
			bytes = getBytesFromStream(is);
			
		} finally {
			if (is != null) {
        		is.close();
  		    }
		}
        return bytes;
    }
	
	public static byte[] getBytesFromStream(InputStream is) throws IOException  {
		byte[] bytes = null;
    	ByteArrayOutputStream baos = null;
    	
    	try {
    		baos = new ByteArrayOutputStream();
    		int bytee;
    	
    		while (-1 != (bytee=is.read())) {
    			baos.write(bytee);
    		}
    		bytes = baos.toByteArray();
    	}
    	catch(Exception exc)
    	{
    		exc.printStackTrace();
    	} finally {
    		if (baos != null) {
    			baos.close();
    		}
    	}
        return bytes;
    }
	
	public static InputStream getStreamFromFile(String path) throws Exception {
        return new FileInputStream(new File(path));
    }
	
	public static void writeDataToFile(String filePath, InputStream data) throws IOException {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(filePath));
			fos.write(getBytesFromStream(data));
		} finally {
			if (fos != null) {
				fos.close();
			}
		}
	}	
	
}
