import time
from cStringIO import StringIO
import pycurl


#URL = "http://localhost:10000/"
URL = "http://freebsd:1234/wsgi-file/usr/local/nginx/buf"


def application(environ, start_response):
    buf = StringIO()

    c = pycurl.Curl()
    c.setopt(pycurl.URL, URL)
    c.setopt(pycurl.WRITEFUNCTION, buf.write)

    m = pycurl.CurlMulti()
    m.add_handle(c)

    log = environ['wsgi.errors']

    log.write('bootstrap')
    while 1:
        ret, num_handles = m.perform()
        log.write('ret: %d, num_handles: %d' % (ret, num_handles))

        if ret != pycurl.E_CALL_MULTI_PERFORM:
            break


    log.write('starting')
    while num_handles:
        log.write('polling')
        state = environ['ngx.poll'](500)
        #time.sleep(0.5)
        yield ''

        conn, flags = state()
        log.write('poll state: %s, %s' % (conn, flags))
        while 1:
            ret, num_handles = m.perform()
            log.write('ret: %d, num_handles: %d' % (ret, num_handles))

            if ret != pycurl.E_CALL_MULTI_PERFORM:
                break


    content_type = c.getinfo(pycurl.CONTENT_TYPE)

    n, success, error = m.info_read()
    if error:
        headers = [
            ('Server', 'Test-read'),
            ('Content-Type', 'text/plain'),
            ('X-Powered-By', 'Python'),
            ]

        start_response('500 Internal Error', headers)
        yield str(error[0][1:])

        return

    headers = [
        ('Server', 'Test-read'),
        ('Content-Type', content_type),
        ('X-Powered-By', 'Python'),
        ]

    start_response('200 OK', headers)
    yield buf.getvalue()

