package ru.redguy.tasks;

import ru.redguy.ATask;
import ru.redguy.Task;

import java.io.IOException;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import java.util.stream.LongStream;


@ATask("17")
public class Task17 extends Task {

    @Override
    public void run() throws IOException, ExecutionException, InterruptedException {
        int pool = 0;
        int parallel = 0;
        int basic = 0;
        ForkJoinPool p = new ForkJoinPool(10);
        for (int run = 0; run < 5; run++) {
            Instant start = Instant.now();
            p.submit(() -> {
                return LongStream.range(1, 99999).parallel()
                        .mapToObj(this::isPrime)
                        .collect(Collectors.toList());
            }).get();
            long time = Instant.now().getEpochSecond() - start.getEpochSecond();
            System.out.println("Pool - Run: "+run+" Time: "+time);
            pool+=time;

            start = Instant.now();
            LongStream.range(1, 99999).parallel()
                    .mapToObj(this::isPrime)
                    .collect(Collectors.toList());
            time = Instant.now().getEpochSecond() - start.getEpochSecond();
            System.out.println("Parallel - Run: "+run+" Time: "+time);
            parallel+=time;

            start = Instant.now();
            LongStream.range(1, 99999)
                    .mapToObj(this::isPrime)
                    .collect(Collectors.toList());
            time = Instant.now().getEpochSecond() - start.getEpochSecond();
            System.out.println("Stream - Run: "+run+" Time: "+time);
            basic+=time;
        }
        System.out.println("Pool avg: "+pool/5);
        System.out.println("Parallel avg: "+parallel/5);
        System.out.println("Stream avg: "+basic/5);
        p.shutdown();
    }


    public boolean isPrime(long number) {
        boolean isPrime = true;
        for(int p = 2; p < number; p++) {
            if(number % p == 0){
                isPrime = false;
                break;
            }
        }
        return isPrime;
    }
}
