#!/usr/bin/python
import os
__file__=os.path.realpath(__file__)
import site
site.addsitedir('/mit/xavid/lib/python2.7/site-packages/')
site.addsitedir(os.path.dirname(__file__))

__requires__ = 'Monkey'
import pkg_resources
pkg_resources.require('Monkey')

import monkey

import sys

import signal, traceback
def quit_handler(signum,frame):
    traceback.print_stack()
signal.signal(signal.SIGQUIT,quit_handler)

def fetch(url, data=None):
    # Load the WSGI application from the config file
    from paste.deploy import loadapp
    appname = 'config:' + os.path.dirname(__file__) + '/development.ini'
    wsgi_app = loadapp(appname)
    
    from bazbase.benchmark import benchmarking

    benchmarking.start(prevent_override=True)

    with benchmarking("Fetching %s < %s" % (url, data)):
        import paste.fixture
        app = paste.fixture.TestApp(wsgi_app, extra_environ=
                                    {'bazjunk.throw_errors': True})
        if data is not None:
            print app.post(url, data)            
        else:
            print app.get(url)


if __name__ == '__main__':
    from bazki import auth
    auth.test_identity = u'Admin'
    
    args = sys.argv[1:]
    profiled = False

    if '--profile' in args:
        args.remove('--profile')
        import cProfile
        from datetime import datetime
        n = datetime.now()
        cProfile.run('fetch(*args)', 'fetch.profile')
        print >>sys.stderr, 'Fetch took', datetime.now()-n
        profiled = True
    else:
        fetch(*args)

    if profiled:
        from pstats import Stats
        s = Stats('fetch.profile', stream=sys.stderr)
        s.strip_dirs()
        s.sort_stats('time')
        #s.sort_stats('cumulative')
        #s.print_stats()
        #s.print_callers()

        print >>sys.stderr, "gprof2dot"
        os.system('/mit/xavid/bin/gprof2dot.py -f pstats fetch.profile -n 1 --skew .05 | dot -Tsvg -o output.svg')
        print >>sys.stderr, "Done."
