package utils;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.apache.axis.encoding.Base64;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.ProcessingInstruction;
 
public class Util {

	// Read of a Binary file from disk
	public static byte[] readBinaryFile(String filename) {
		byte buf[] = null;
		try {
			FileInputStream fis = new FileInputStream(filename);
			buf = new byte[fis.available()];
			DataInputStream dis = new DataInputStream(fis);
			dis.read(buf);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return buf;
	}
 
	// Read of a Binary file from disk and encodes to Base64
	public static String readBinaryFileB64(String filename) {
		byte buf[] = null;
		try {
			FileInputStream fis = new FileInputStream(filename);
			buf = new byte[fis.available()];
			DataInputStream dis = new DataInputStream(fis);
			dis.read(buf);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return Base64.encode(buf);
	}

	// Write of a Binary file to disk
	public static void writeBinaryFile(String destFilename, byte[] data) {
		try {
			FileOutputStream fos = new FileOutputStream(destFilename);
			DataOutputStream dos = new DataOutputStream(fos);
			dos.write(data);
			System.out.println("File saved successfully on: " + destFilename);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	// Write of a Binary file encoded in Base64 to disk
	public static void writeBinaryFileB64(String destFilename, String data) {
		try {
			FileOutputStream fos = new FileOutputStream(destFilename);
			DataOutputStream dos = new DataOutputStream(fos);
			dos.write(Base64.decode(data));
			System.out.println("File saved successfully on: " + destFilename);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	// Pretty print XML using a style sheet
	public static String serialize(Document doc, String xsl) {
		Element element = doc.getDocumentElement();
		ProcessingInstruction pi = doc.createProcessingInstruction("xml-stylesheet", "type='text/xsl' href='"
				+ xsl + "'");
		element.getParentNode().insertBefore(pi, element);
		return serialize(doc);
	}

	// Pretty print XML
	public static String serialize(Document doc) {
		StringWriter sw = new StringWriter();
		OutputFormat format = new OutputFormat("xml", "iso-8859-1", true);
		format.setStandalone(false);
		format.setOmitXMLDeclaration(false);
		format.setOmitDocumentType(false);
		format.setIndent(3);
		format.setLineSeparator(System.getProperty("line.separator"));
		XMLSerializer serial = new XMLSerializer(sw, format);
		try {
			serial.asDOMSerializer();
			serial.serialize(doc);
			sw.flush();
		} catch (IOException e) {
			System.err.println(e);
		} catch (Exception e) {
			System.err.println(e);
		}
		return (sw.toString());
	}
	
	// Read file
    public static String readFile(String fileName)  throws Exception 
    {
    	File file = new File(fileName);
    	FileInputStream fis = new FileInputStream(file);
    	byte[] buf = new byte[(int)file.length()];
      	fis.read(buf);
    	return new String(buf);
    }
    

    // Write text file
	public static void writeTextFile(String contents, String file) throws IOException 
	{
		java.io.File f = new File(file);
		PrintWriter out = new PrintWriter(new FileWriter(f));
		out.print(contents);
		out.close();
		System.out.println("File saved successfully on: " + file);
	}
	
	
	
	/** 
	 * Returns the contents of the file in a byte array.
	 */
    public static byte[] getBytesFromFile(String path) throws IOException {
    	
    	InputStream is = new FileInputStream(path);
        byte[] bytes = getBytes(is);
        is.close();

        return bytes;
    }
    
    
    /**
     * Gets a byte array from an InputStream.
     * @param is InputStream
     * @return byte[]
     * @throws IOException
     */
    public static byte[] getBytes(InputStream is) throws IOException {
    
    	ByteArrayOutputStream baos = new ByteArrayOutputStream();
    	
    	int bytee;
    	while (-1!=(bytee=is.read()))
    	{
    	   baos.write(bytee);
    	}
    	baos.close();
    	byte[] bytes = baos.toByteArray();

        is.close();
        return bytes;
    }
	
	/**
	 * Renombra un fitxer
	 * @param oldName path+nom del fitxer a renombrar
	 * @param newName nou path+nom del nou fitxer
	 * @return true -> el renombrament d'ha portat a terme correctament; false -> en cas contrari
	 */
	public static boolean renameFile(String oldName, String newName){
		//fitxer a renombrar
		File oldFile = new File(oldName);
		//renombrem el fitxer
		boolean success = oldFile.renameTo(new File(newName));
		if(success){
			//si s'ha renombrat correctament, esborrem l'original
			oldFile.delete();
		}
		return success;
	}
	
}

