#!/usr/bin/env python

"""Scrape ADP from MockDraftCentral, export in CSV format.
"""

import argparse
import cStringIO
import sys

import unicodecsv

from mdc_utils import Scraper


__version__ = '0.1'
__author__ = 'Matt Dennewitz'


def handle_spilled_milk(e_type, value, traceback):
    sys.exit('Error: ' + value.message)

sys.excepthook = handle_spilled_milk


def main():
    """Do it
    """

    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--username', dest='username', required=True,
                        help='Mock Draft Central username')
    parser.add_argument('-p', '--password', dest='password', required=True,
                        help='Mock Draft Central password')
    parser.add_argument('--headers', dest='headers', action='store_true',
                        default=False, help='Include CSV headers in export')
    args = parser.parse_args()

    # scccraaaaaaaape
    scraper = Scraper(username=args.username, password=args.password)

    # write ADP data to IO in CSV format
    io = cStringIO.StringIO()
    writer = unicodecsv.writer(io, encoding='utf-8')

    if args.headers:
        writer.writerow(scraper.KEYS)

    for row in scraper:
        writer.writerow(row)

    io.seek(0)

    # yell into the void
    for line in io:
        sys.stdout.write(line)


if __name__ == '__main__':
    main()
