/*
 * 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.oscore.logging.core.itest;

import static org.junit.Assert.assertTrue;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.Security;

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

import com.scytl.products.oscore.logging.api.domain.Level;
import com.scytl.products.oscore.logging.api.domain.LogContent;
import com.scytl.products.oscore.logging.api.domain.LogContent.LogContentBuilder;
import com.scytl.products.oscore.logging.api.factory.SecureLoggingFactory;
import com.scytl.products.oscore.logging.api.formatter.MessageFormatter;
import com.scytl.products.oscore.logging.api.writer.SecureLoggingWriter;
import com.scytl.products.oscore.logging.core.factory.SecureLoggingFactoryLog4j;
import com.scytl.products.oscore.logging.core.formatter.SplunkFormatter;
import com.scytl.products.oscore.logging.core.provider.TransactionInfoProvider;

/**
 * Integration test to verify the logging system case of use
 */
public class SecureLoggingIntegrationTest {
    private Path folder;

    @BeforeClass
    public static void beforeClass() {
        if (Security
            .getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    @Before
    public void setUp() {
        folder = Paths.get("target/logs");
    }

    @Test
    public void itShouldLogWithSecureLog4() throws Exception {
        TransactionInfoProvider provider = new TransactionInfoProvider();

        provider.generate("FAKE_TENANT", "192.168.1.1", "127.0.0.1");

        MessageFormatter formatter =
            new SplunkFormatter("APPLICATION", "MODULE", provider);

        SecureLoggingFactory loggerFactory =
            new SecureLoggingFactoryLog4j(formatter);

        LogContentBuilder builder = new LogContentBuilder();
        builder.logEvent(LogEventTest.TEST_EVENT);
        builder.objectType("objectType");
        builder.objectId("objectId");
        builder.user("userID");
        builder.electionEvent("123456789");
        builder.additionalInfo("message", "test compatibility log4j");
        builder.additionalInfo("errorcode", "1");
        builder.additionalInfo("exception", "no error");

        LogContent content = builder.createLogInfo();

        SecureLoggingWriter writer =
            loggerFactory.getLogger("SecureLogger");

        writer.log(Level.INFO, content);

        Path file = folder.resolve("secure_log4j.log").toAbsolutePath();

        assertTrue(Files.size(file) > 0);
    }
}
