#!/usr/bin/python3

import sys
import time
import argparse

from maillist.validators import EmailAddressValidator
from maillist import processors


def main(input, output, verbose, max_workers, validators=[]):
    t0 = time.time()
    num_processed = processors.process(input, output, validators, max_workers=max_workers)
    elapsed = time.time() - t0
    if verbose:
        msg = '\n{} emails verified in {:.2f}s using {} worker threads'
        print(msg.format(num_processed, elapsed, max_workers))


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Creates a maillist of unique email addresses together with their respective counts.')
    parser.add_argument(
        '-i', '--input',
        type=argparse.FileType('r'), default=sys.stdin,
        metavar='INPUT',
        help='The list of email addresses')
    parser.add_argument(
        '-o', '--out',
        type=argparse.FileType('w'), default=sys.stdout,
        metavar='OUTPUT',
        help='The file where the unparseable lines should be written (default: write to stdout)')
    parser.add_argument(
        '-c', '--check',
        action='store_true',
        help='Run all validator checks')
    parser.add_argument(
        '-m', '--max_workers',
        type=int,
        default=20,
        metavar='MAX_WORKERS',
        help='Maximum number of worker threads to use'
    )
    parser.add_argument(
        '-v', '--verbose',
        action='store_true',
        help='output parse errors')
    args = parser.parse_args()
    if args.check:
        validators = EmailAddressValidator.plugins
    else:
        validators = []
    main(args.input, args.out, args.verbose, args.max_workers, validators=validators)
