"""Through the magic of monkeypatching, requests works with diesel.

It's a hack.

"""
import httplib
import sys

import diesel
from diesel.resolver import DNSResolutionError
from OpenSSL import SSL

try:
    from requests.packages.urllib3 import connectionpool
    import requests
except ImportError:
    connectionpool = None


_enc = sys.getdefaultencoding()

class SocketFileLike(diesel.Client):
    """Enough of a stand-in for a socket/file-like object.

    At least enough to satisfy the requests test suite.

    """
    def __init__(self, host, port, **kw):
        super(SocketFileLike, self).__init__(host, port, **kw)
        self._extra = ""
        self._timeout = None

    def makefile(self, mode, buffering):
        return self

    @diesel.call
    def read(self, size=None):
        assert size is not None, "Sorry, have to pass a size to read()"
        if size == 0:
            return ''
        evt, data = diesel.first(sleep=self._timeout, receive=size)
        if evt == 'sleep':
            self._timeout = None
            raise requests.exceptions.Timeout
        return data

    @diesel.call
    def readline(self, max_size=None):
        evt, line = diesel.first(sleep=self._timeout, until='\n')
        if evt == 'sleep':
            self._timeout = None
            raise requests.exceptions.Timeout
        if max_size:
            line = "".join([self._extra, line])
            nl = line.find('\n') + 1
            if nl > max_size:
                nl = max_size
            line, self._extra = line[:nl], line[nl:]
        return line

    @diesel.call
    def write(self, data):
        diesel.send(data.encode(_enc))
    sendall = write

    @diesel.call
    def next(self):
        data = self.readline()
        if not data:
            raise StopIteration()
        return data

    def __iter__(self):
        return self

    def settimeout(self, n):
        self._timeout = n

class HTTPConnection(httplib.HTTPConnection):
    def connect(self):
        try:
            self.sock = SocketFileLike(self.host, self.port)
        except DNSResolutionError:
            raise requests.ConnectionError

class HTTPSConnection(httplib.HTTPSConnection):
    def connect(self):
        try:
            kw = {'ssl_ctx': SSL.Context(SSL.SSLv23_METHOD)}
            self.sock = SocketFileLike(self.host, self.port, **kw)
        except DNSResolutionError:
            raise requests.ConnectionError

class RequestsLibNotFound(Exception):pass

def enable_requests():
    """This is monkeypatching."""
    if not connectionpool:
        msg = "You need to install requests (http://python-requests.org)"
        raise RequestsLibNotFound(msg)
    connectionpool.HTTPConnection = HTTPConnection
    connectionpool.HTTPSConnection = HTTPSConnection
@@ -364,28 +364,24 @@
 class Socket
-File
 Like(diesel.
@@ -400,57 +400,34 @@
  %22%22%22
-Enough of a stand-in for a
+A
  socket
-/file
 -like 
-objec
+diesel Clien
 t.%0A%0A
@@ -481,16 +481,96 @@
 t suite.
+ Its primary job is%0A    to return a FileLike instance when %60makefile%60 is called.
 %0A%0A    %22%22
@@ -629,28 +629,24 @@
 super(Socket
-File
 Like, self).
@@ -690,109 +690,922 @@
 lf._
-extra = %22%22%0A        self._timeout = None%0A%0A    def makefile(self, mode, buffering):%0A        return self
+timeout = None%0A%0A    def makefile(self, mode, buffering):%0A        return FileLike(self, mode, buffering, self._timeout)%0A%0A    def settimeout(self, n):%0A        self._timeout = n%0A%0A    @diesel.call%0A    def sendall(self, data):%0A        diesel.send(data.encode(_enc))%0A%0Aclass FileLike(object):%0A    %22%22%22Gives you a file-like interface from a diesel Client.%22%22%22%0A    def __init__(self, client, mode, buffering, timeout):%0A        self._client = client%0A        self.mode = mode%0A        self.buffering = buffering%0A        self._extra = %22%22%0A        self._timeout = timeout%0A%0A    # Properties To Stand In For diesel Client%0A    # ----------------------------------------%0A%0A    @property%0A    def conn(self):%0A        return self._client.conn%0A%0A    @property%0A    def connected(self):%0A        return self._client.connected%0A%0A    @property%0A    def is_closed(self):%0A        return self._client.is_closed%0A%0A    # File-Like API%0A    # -------------
 %0A%0A  
@@ -2515,28 +2515,8 @@
 nc))
-%0A    sendall = write
 %0A%0A  
@@ -2710,34 +2710,26 @@
     def 
-settimeout
+close
 (self
-, n
 ):%0A     
@@ -2737,27 +2737,30 @@
   self._
-timeout = n
+client.close()
 %0A%0Aclass 
@@ -2857,36 +2857,32 @@
 lf.sock = Socket
-File
 Like(self.host, 
@@ -3146,20 +3146,16 @@
 = Socket
-File
 Like(sel
@@ -3585,24 +3585,26 @@
 ection = HTTPSConnection
+%0A%0A

Clean up the requests monkey patch a bit.