/*
 * 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.au.services.domain.model.authentication;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.products.oscore.logging.api.writer.SecureLoggingWriter;
import com.scytl.products.ov.au.services.domain.model.adminboard.AdminBoard;
import com.scytl.products.ov.au.services.domain.model.adminboard.AdminBoardRepository;
import com.scytl.products.ov.au.services.domain.model.material.Credential;
import com.scytl.products.ov.au.services.domain.model.material.CredentialRepository;
import com.scytl.products.ov.commons.beans.domain.model.certificate.CertificateEntity;
import com.scytl.products.ov.commons.beans.exceptions.ResourceNotFoundException;
import com.scytl.products.ov.commons.beans.validation.CryptographicOperationException;
import com.scytl.products.ov.commons.crypto.SignatureForObjectService;
import com.scytl.products.ov.commons.infrastructure.remote.service.RemoteCertificateService;
import com.scytl.products.ov.commons.random.RandomType;
import com.scytl.products.ov.commons.tracking.TrackIdInstance;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;

import java.nio.charset.StandardCharsets;

import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.anyVararg;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class CredentialInformationFactoryTest {

    public static final String ELECTION_EVENT_ID = "100";

    public static final String TENANT_ID = "100";

    public static final String ADMIN_BOARD_ID = "100";

    private static final String JSON = "{}";

    public static final String CREDENTIAL_ID = "100";

    public static final int RANDOM_VALUE_LENGTH = 16;

    public static final byte[] BYTES = "signature".getBytes(StandardCharsets.UTF_8);

    @Mock
    private CredentialRepository credentialRepository;

    @Mock
    private SignatureForObjectService signatureService;

    @Mock
    private AuthenticationCertsRepository authenticationCertsRepository;

    @Mock
    private TrackIdInstance trackId;

    @Mock
    private SecureLoggingWriter secureLoggerWriter;

    @Mock
    private AdminBoardRepository adminBoardRepository;

    @Mock
    private RemoteCertificateService remoteCertificateService;

    @Mock
    private AuthenticationCerts authenticationCerts;

    @Mock
    private CertificateEntity certificateEntity;

    @Mock
    private AdminBoard adminBoard;

    @Mock
    private Credential credential;

    @InjectMocks
    private CredentialInformationFactory credentialInformationFactory = new CredentialInformationFactory();

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this.getClass());
    }

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

    @Test
    public void buildCertificates()
            throws CryptographicOperationException, GeneralCryptoLibException, ResourceNotFoundException {

        mockCertificatesInfo();
        assertNotNull(credentialInformationFactory.buildAuthenticationCertificates(TENANT_ID, ELECTION_EVENT_ID));
    }

    @Test
    public void buildCertificatesResourceNotFound()
            throws CryptographicOperationException, GeneralCryptoLibException, ResourceNotFoundException {

        expectedException.expect(ResourceNotFoundException.class);
        when(authenticationCertsRepository.findByTenantIdElectionEventId(anyString(), anyString()))
            .thenThrow(new ResourceNotFoundException("exception"));
        credentialInformationFactory.buildAuthenticationCertificates(TENANT_ID, ELECTION_EVENT_ID);
    }

    @Test
    public void buildCredentialInformation()
            throws CryptographicOperationException, GeneralCryptoLibException, ResourceNotFoundException {

        when(credentialRepository.findByTenantIdElectionEventIdCredentialId(anyString(), anyString(), anyString()))
            .thenReturn(credential);
        when(signatureService.sign(anyString(), anyString(), anyString(), anyString(), anyVararg())).thenReturn(BYTES);
        mockCertificatesInfo();
        assertNotNull(credentialInformationFactory.buildCredentialInformation(TENANT_ID, ELECTION_EVENT_ID,
            CREDENTIAL_ID, RandomType.BYTES, RANDOM_VALUE_LENGTH));

    }

    @Test
    public void buildCredentialInformationNotFoundCredentials()
            throws CryptographicOperationException, GeneralCryptoLibException, ResourceNotFoundException {

        expectedException.expect(ResourceNotFoundException.class);
        when(credentialRepository.findByTenantIdElectionEventIdCredentialId(anyString(), anyString(), anyString()))
            .thenThrow(new ResourceNotFoundException("exception"));

        credentialInformationFactory.buildCredentialInformation(TENANT_ID, ELECTION_EVENT_ID, CREDENTIAL_ID,
            RandomType.BYTES, RANDOM_VALUE_LENGTH);

    }

    @Test
    public void buildCredentialInformationCryptoLibException()
            throws CryptographicOperationException, GeneralCryptoLibException, ResourceNotFoundException {

        expectedException.expect(CryptographicOperationException.class);
        when(credentialRepository.findByTenantIdElectionEventIdCredentialId(anyString(), anyString(), anyString()))
                .thenReturn(credential);
        when(signatureService.sign(anyString(), anyString(), anyString(), anyString(), anyVararg()))
        .thenThrow(new CryptographicOperationException("exception"));
        mockCertificatesInfo();
        assertNotNull(credentialInformationFactory.buildCredentialInformation(TENANT_ID, ELECTION_EVENT_ID,
                CREDENTIAL_ID, RandomType.BYTES, RANDOM_VALUE_LENGTH));

    }

    @Test
    public void buildCredentialInformationCrypoGraphicOperationException()
            throws CryptographicOperationException, GeneralCryptoLibException, ResourceNotFoundException {

        expectedException.expect(CryptographicOperationException.class);
        when(credentialRepository.findByTenantIdElectionEventIdCredentialId(anyString(), anyString(), anyString()))
                .thenReturn(credential);
        when(signatureService.sign(anyString(), anyString(), anyString(), anyString(), anyVararg()))
        .thenThrow(new CryptographicOperationException("exception"));
        mockCertificatesInfo();
        assertNotNull(credentialInformationFactory.buildCredentialInformation(TENANT_ID, ELECTION_EVENT_ID,
                CREDENTIAL_ID, RandomType.BYTES, RANDOM_VALUE_LENGTH));

    }

    private void mockCertificatesInfo() throws ResourceNotFoundException {
        when(authenticationCertsRepository.findByTenantIdElectionEventId(anyString(), anyString()))
            .thenReturn(authenticationCerts);
        when(adminBoardRepository.findByTenantIdElectionEventId(anyString(), anyString())).thenReturn(adminBoard);
        when(adminBoard.getAdminBoardId()).thenReturn(ADMIN_BOARD_ID);
        when(authenticationCerts.getJson()).thenReturn(JSON);
        when(remoteCertificateService.getAdminBoardCertificate(anyString())).thenReturn(certificateEntity);
        when(remoteCertificateService.getTenantCACertificate(anyString())).thenReturn(certificateEntity);
        when(certificateEntity.getCertificateContent()).thenReturn("certificateContent");
    }

}
