package net.catcert.psa.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class Utils {

	public static byte[] resourceAsBytes(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 resourceAsStream(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(filePath);
			fos.write(getBytesFromStream(data));
		} finally {
			if (fos != null) {
				fos.close();
			}
		}
	}

	/**
	 * Writes a file with provided bytes
	 * @param filePath
	 * @param data
	 * @throws IOException
	 */
	public static void writeDataToFile(String filePath, byte[] data) throws IOException {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(filePath));
			fos.write(data);
		} finally {
			if (fos != null) {
				fos.close();
			}
		}
	}

	/**
	 * This method reads a certificate from an inputStream 
	 * The certificate can be either binary or base64 encoded.
	 * @param file
	 * @return
	 * @throws Exception 
	 */
	public static X509Certificate getX509Certificate(String filePath) throws Exception { 

		InputStream is = new FileInputStream(filePath);
		CertificateFactory cf = CertificateFactory.getInstance("X.509"); 
		X509Certificate cert = (X509Certificate)cf.generateCertificate(is); 
		return cert; 

	}

	/**
	 * Return Issuer in format which PSA needs for his requests
	 * @param cert
	 * @return
	 */
	public static String getIssuerForPSARequest(X509Certificate cert){
		String issuerName = cert.getIssuerX500Principal().getName("RFC1779");
		issuerName = issuerName.replaceAll(", ", ",");
		issuerName = issuerName.replaceAll("\"", "");
		return issuerName;
	}




}
