/*
 * 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.cryptolib.symmetric.cipher.factory;

import static mockit.Deencapsulation.getField;
import static org.junit.Assert.assertEquals;

import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.scytl.cryptolib.api.exceptions.CryptoLibException;
import com.scytl.cryptolib.commons.utils.system.OperatingSystem;
import com.scytl.cryptolib.primitives.securerandom.configuration.ConfigSecureRandomAlgorithmAndProvider;
import com.scytl.cryptolib.symmetric.cipher.configuration.ConfigSymmetricCipherAlgorithmAndSpec;
import com.scytl.cryptolib.symmetric.cipher.configuration.SymmetricCipherPolicy;

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

    @AfterClass
    public static void removeBouncyCastleProvider() {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }

    @Test
    public void whenCreateSymmetricCipherFactoryUsingPolicyAesGcmNoPaddingAndBc() {

        SymmetricCipherFactory SymmetricCipherFactoryByPolicy =
            new SymmetricCipherFactory(
                getSymmetricCipherPolicyAesGcmNoPaddingAndBc());

        SymmetricCipherPolicy expectedSymmetricCipherPolicy =
            getField(SymmetricCipherFactoryByPolicy,
                "_symmetricCipherPolicy");

        assertEquals(getSymmetricCipherPolicyAesGcmNoPaddingAndBc()
            .getSymmetricCipherAlgorithmAndSpec(),
            expectedSymmetricCipherPolicy
                .getSymmetricCipherAlgorithmAndSpec());
    }

    private SymmetricCipherPolicy getSymmetricCipherPolicyAesGcmNoPaddingAndBc() {
        return new SymmetricCipherPolicy() {

            @Override
            public ConfigSecureRandomAlgorithmAndProvider getSecureRandomAlgorithmAndProvider() {
                return getSecureRandomConfig();
            }

            @Override
            public ConfigSymmetricCipherAlgorithmAndSpec getSymmetricCipherAlgorithmAndSpec() {
                return ConfigSymmetricCipherAlgorithmAndSpec.AESwithGCMandNOPADDING_96_128_BC;
            }
        };
    }

    private static ConfigSecureRandomAlgorithmAndProvider getSecureRandomConfig() {

        switch (OperatingSystem.current()) {

        case WINDOWS:
            return ConfigSecureRandomAlgorithmAndProvider.PRNG_SUN_MSCAPI;
        case LINUX:
            return ConfigSecureRandomAlgorithmAndProvider.NATIVE_PRNG_SUN;
        default:
            throw new CryptoLibException("OS not supported.");
        }
    }

}
