/*
 * 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.commons.sign;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

import java.security.KeyPair;

import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.asymmetric.service.AsymmetricService;
import com.scytl.products.ov.commons.beans.TestBean;
import com.scytl.products.ov.commons.beans.TestNonSerializableBean;
import com.scytl.products.ov.commons.configuration.JSONSignatureConfiguration;

public class JSONSignerTest {

	public static final String FOO_BAR = "fooBar";

	public static final int TWO = 2;

	public static final int NUMBER_OF_PARTS_OF_JSON_WEB_SIGNATURE = 3;

	private static TestBean bean;

	private static TestNonSerializableBean nonSerializableBean;

	private static KeyPair keyPairForSigning;

	private static JSONSigner sut;

	@Rule
	public ExpectedException expectedException = ExpectedException.none();

	@BeforeClass
	public static void setUp() throws GeneralCryptoLibException {

		sut = new JSONSigner(JSONSignatureConfiguration.RSA_PSS_SHA256);

		bean = new TestBean();
		bean.setFieldOne(FOO_BAR);
		bean.setFieldTwo(TWO);

		nonSerializableBean = new TestNonSerializableBean();
		nonSerializableBean.setFieldOne(FOO_BAR);
		nonSerializableBean.setFieldTwo(TWO);

		AsymmetricService asymmetricService = new AsymmetricService();
		keyPairForSigning = asymmetricService.getKeyPairForSigning();
	}

	@Test
	public void sign_correctly_a_given_serializable_object() {

		String signedBean = sut.sign(keyPairForSigning.getPrivate(), bean);

		assertThat(signedBean.isEmpty(), is(false));
		assertThat(signedBean.split("\\.").length, is(NUMBER_OF_PARTS_OF_JSON_WEB_SIGNATURE));
	}

	@Test
	public void sign_null() {

		String signedNull = sut.sign(keyPairForSigning.getPrivate(), null);

		assertThat(signedNull.isEmpty(), is(false));
		assertThat(signedNull.split("\\.").length, is(NUMBER_OF_PARTS_OF_JSON_WEB_SIGNATURE));

	}

	@Test
	public void sign_a_string() {

		String signedString = sut.sign(keyPairForSigning.getPrivate(), FOO_BAR);

		assertThat(signedString.isEmpty(), is(false));
		assertThat(signedString.split("\\.").length, is(NUMBER_OF_PARTS_OF_JSON_WEB_SIGNATURE));

	}

	@Test
	public void sign_an_integer() {

		String signedInteger = sut.sign(keyPairForSigning.getPrivate(), TWO);

		assertThat(signedInteger.isEmpty(), is(false));
		assertThat(signedInteger.split("\\.").length, is(NUMBER_OF_PARTS_OF_JSON_WEB_SIGNATURE));

	}

	@Test
	public void throw_an_exception_with_no_serializable_object() {

		expectedException.expect(IllegalStateException.class);
		sut.sign(keyPairForSigning.getPrivate(), nonSerializableBean);
	}
}
