"""
qp/lib/push.py
"""
from qp.fill.form import Form
from qp.lib.util import rand_str
import sys

try:
    from httplib import HTTPConnection, HTTPSConnection
except ImportError:
    from http.client import HTTPConnection, HTTPSConnection

crlf = '\r\n'


class Pusher (object):

    def __init__(self):
        self.parts = ['']
        self.boundary = rand_str(20)

    def add_data_part (self, name, value):
        self.parts.append(crlf.join([
            'Content-Disposition: form-data; name="%s"' % name,
            '',
            str(value)]))

    def add_file_part (self, name, file, file_name, content_type):
        content = file.read()
        self.parts.append(crlf.join([
            'Content-Disposition: form-data; name="%s"; filename="%s"' % (name, file_name),
            'Content-Type: %s' % content_type,
            '',
            content]))

    def add_token(self, user):
        self.add_data_part(Form.TOKEN_NAME, user.get_tokens().new_token())

    def get_boundary(self):
        return self.boundary

    def get_body(self):
        boundary = self.get_boundary()
        body = (crlf + '--' + boundary + crlf).join(map(str, self.parts)) + crlf + '--' + boundary + '--' + crlf
        return body

    def retrieve(self, method, scheme, host, port, path, agent=None, timeout=10):
        assert scheme in ('http', 'https')
        if scheme == 'https':
            connection = HTTPSConnection(str(host), str(port), timeout=timeout)
        else:
            connection = HTTPConnection(str(host), str(port), timeout=timeout)
        headers = dict()
        headers['Content-type'] = 'multipart/form-data; boundary=%s' % self.get_boundary()
        body = self.get_body()
        headers['Content-length'] = len(body)
        if agent is not None:
            headers['User-agent'] = agent
        connection.request(method, path, body=body, headers=headers)
        return connection.getresponse()

