/*
 * 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.config.model.authentication.service;

import com.scytl.products.ov.config.model.authentication.ProvidedChallenges;
import org.junit.Test;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;


public class SequentialProvidedChallengeSourceTest {

    @Test
    public void returnCorrectNextValue() throws URISyntaxException {
        final URL url = this.getClass().getResource("/aliasDataSample.csv");
        Path aliasesPath = new File(url.toURI()).toPath();
        ProvidedChallengeSource source = new SequentialProvidedChallengeSource(aliasesPath);
        ProvidedChallenges challenges = source.next();
        String alias = challenges.getAlias();
        assertEquals("alias1", alias);
    }

    @Test
    public void returnCorrectNextValuesForThreads() throws URISyntaxException, InterruptedException {
        final URL url = this.getClass().getResource("/aliasDataSample.csv");
        Path aliasesPath = new File(url.toURI()).toPath();
        ProvidedChallengeSource source = new SequentialProvidedChallengeSource(aliasesPath);


        ExecutorService executor = Executors.newFixedThreadPool(10);
        CountDownLatch latch = new CountDownLatch(10);


        Queue<String> queue = new ConcurrentLinkedQueue<String>();
        for (int i = 0; i < 10; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    queue.add(source.next().getAlias());
                    latch.countDown();
                }
            });
        }

        latch.await();

        assertTrue(queue.contains("alias1"));
        assertTrue(queue.contains("alias2"));
        assertTrue(queue.contains("alias3"));
        assertTrue(queue.contains("alias4"));
        assertTrue(queue.contains("alias5"));
        assertTrue(queue.contains("alias6"));
        assertTrue(queue.contains("alias7"));
        assertTrue(queue.contains("alias8"));
        assertTrue(queue.contains("alias9"));
        assertTrue(queue.contains("alias10"));
    }
}