package meerkat.bulletinboard;

import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import meerkat.comm.CommunicationException;
import meerkat.protobuf.Voting.BulletinBoardClientParams;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.security.SignatureException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * Created by Arbel Deutsch Peled on 05-Dec-15.
 */
public class SingleServerBulletinBoardClientIntegrationTest {

    // Server data

    private static final String PROP_GETTY_URL = "gretty.httpBaseURI";
    private static final String DEFAULT_BASE_URL = "http://localhost:8081";
    private static final String BASE_URL =  System.getProperty(PROP_GETTY_URL, DEFAULT_BASE_URL);

    private static final int THREAD_NUM = 3;
    private static final long FAIL_DELAY = 3000;
    private static final long SUBSCRIPTION_INTERVAL = 500;

    // Testers
    private GenericBulletinBoardClientTester clientTest;
    private GenericSubscriptionClientTester subscriptionTester;

    public SingleServerBulletinBoardClientIntegrationTest(){

        SingleServerBulletinBoardClient client = new SingleServerBulletinBoardClient(THREAD_NUM, FAIL_DELAY, SUBSCRIPTION_INTERVAL);

        List<String> testDB = new LinkedList<>();
        testDB.add(BASE_URL);

        client.init(BulletinBoardClientParams.newBuilder()
                .addAllBulletinBoardAddress(testDB)
                .setMinRedundancy((float) 1.0)
                .build());

        clientTest = new GenericBulletinBoardClientTester(client, 981541);
        subscriptionTester = new GenericSubscriptionClientTester(client);

    }

    // Test methods

    /**
     * Takes care of initializing the client and the test resources
     */
    @Before
    public void init(){

        clientTest.init();

    }

    /**
     * Closes the client and makes sure the test fails when an exception occurred in a separate thread
     */

    @After
    public void close() {

        clientTest.close();

    }

    @Test
    public void testPost() {

        clientTest.testPost();

    }

    @Test
    public void testBatchPost() throws CommunicationException, SignatureException, InterruptedException {

        clientTest.testBatchPost();
    }

    @Test
    public void testCompleteBatchPost() throws CommunicationException, SignatureException, InterruptedException {

        clientTest.testCompleteBatchPost();

    }

    @Test
    public void testSubscription() throws SignatureException, CommunicationException {

        subscriptionTester.init();
        subscriptionTester.subscriptionTest();
        subscriptionTester.close();

    }

}
