#!/usr/bin/env python3
"""Calculate the sum of primes below a given integer in parallel.

Website: https://www.parallelpython.com
License: Apache-2.0 (see LICENSE and NOTICE)

Usage:
    python sum_primes.py [ncpus]

[ncpus] - number of workers to run in parallel;
if omitted, it is set to the number of processors in the system.
"""

import math
import sys

import pp


def isprime(n):
    """Return True if n is prime, False otherwise."""
    if not isinstance(n, int):
        raise TypeError("argument passed to isprime is not of 'int' type")
    if n < 2:
        return False
    if n == 2:
        return True
    max_i = int(math.ceil(math.sqrt(n)))
    i = 2
    while i <= max_i:
        if n % i == 0:
            return False
        i += 1
    return True


def sum_primes(n):
    """Calculate the sum of all primes below the given integer n."""
    return sum(x for x in range(2, n) if isprime(x))


def main():
    print("""Usage: python sum_primes.py [ncpus]
    [ncpus] - the number of workers to run in parallel,
    if omitted it will be set to the number of processors in the system""")

    # tuple of all parallel python servers to connect with
    ppservers = ()
    # ppservers = ("127.0.0.1:60000",)

    if len(sys.argv) > 1:
        ncpus = int(sys.argv[1])
        # Create a jobserver with ncpus workers
        job_server = pp.Server(ncpus, ppservers=ppservers)
    else:
        # Create a jobserver with automatically detected number of workers
        job_server = pp.Server(ppservers=ppservers)

    print("Starting pp with", job_server.get_ncpus(), "workers")

    # Submit a job of calculating sum_primes(100) for execution.
    # sum_primes - the function
    # (100,) - tuple with arguments for sum_primes
    # (isprime,) - tuple with functions on which the function depends
    # ("math",) - tuple with module names which must be imported before
    #             sum_primes execution
    # Execution starts as soon as one of the workers becomes available
    job1 = job_server.submit(sum_primes, (100,), (isprime,), ("math",))

    # Retrieve the result calculated by job1.
    # The value of job1() is the same as sum_primes(100).
    # If the job has not been finished yet, execution will
    # wait here until the result is available.
    result = job1()

    print("Sum of primes below 100 is", result)

    # The following submits 8 jobs and then retrieves the results.
    inputs = (100000, 100100, 100200, 100300, 100400, 100500, 100600, 100700)
    jobs = [(i, job_server.submit(sum_primes, (i,), (isprime,), ("math",)))
            for i in inputs]

    for i, job in jobs:
        print("Sum of primes below", i, "is", job())

    job_server.print_stats()
    job_server.destroy()


if __name__ == "__main__":
    main()
