/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.utils;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.Security;

import org.apache.commons.io.IOUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest;
import org.junit.BeforeClass;
import org.junit.Test;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.products.ov.config.exceptions.ConfigurationEngineException;

public class PemUtilsTest {

	private static final Charset CHAR_SET = StandardCharsets.UTF_8;

	private static final String NEWLINE = "\n";

	private static final String RETURN = "\r";

	private static final String EMPTY_STRING = "";

	private static final String CSR_PATH = "/pem/csr.pem";

	@BeforeClass
	public static void setUp() throws GeneralCryptoLibException {
		Security.addProvider(new BouncyCastleProvider());
	}

	@Test
	public void testReadingCsrFromAndWritingToPem() throws IOException, GeneralCryptoLibException, ConfigurationEngineException {

		InputStream inStream = getClass().getResourceAsStream(CSR_PATH);
		String pemStrIn = IOUtils.toString(inStream, CHAR_SET);

		JcaPKCS10CertificationRequest csr = PemUtils.csrFromPem(pemStrIn);
		String pemStrOut = PemUtils.csrToPem(csr);

		assertEquals(removeOsDependentSymbols(pemStrIn), removeOsDependentSymbols(pemStrOut));
	}

	private String removeOsDependentSymbols(final String str) {
		return str.replace(NEWLINE, EMPTY_STRING).replace(RETURN, EMPTY_STRING);
	}
}
