import urllib
import netlib.http
from textwrap import dedent


def curl_command(flow):
    data = "curl "

    for k, v in flow.request.headers.fields:
        data += "-H '%s:%s' " % (k, v)

    if flow.request.method != "GET":
        data += "-X %s " % flow.request.method

    full_url = flow.request.scheme + "://" + flow.request.host + flow.request.path
    data += "'%s'" % full_url

    if flow.request.content:
        data += " --data-binary '%s'" % flow.request.content

    return data


def python_code(flow):
    code = dedent("""
        import requests

        url = '{url}'
        {headers}{params}{data}
        response = requests.request(
            method='{method}',
            url=url,{args}
        )

        print(response.text)
    """).strip()

    components = map(lambda x: urllib.quote(x, safe=""), flow.request.path_components)
    url = flow.request.scheme + "://" + flow.request.host + "/" + "/".join(components)

    args = ""
    headers = ""
    if flow.request.headers:
        lines = ["    '%s': '%s',\n" % (k, v) for k, v in flow.request.headers.fields]
        headers += "\nheaders = {\n%s}\n" % "".join(lines)
        args += "\n    headers=headers,"

    params = ""
    if flow.request.query:
        lines = ["    '%s': '%s',\n" % (k, v) for k, v in flow.request.query]
        params = "\nparams = {\n%s}\n" % "".join(lines)
        args += "\n    params=params,"

    data = ""
    if flow.request.body:
        data = "\ndata = '''%s'''\n" % flow.request.body
        args += "\n    data=data,"

    code = code.format(
        url=url,
        headers=headers,
        params=params,
        data=data,
        method=flow.request.method,
        args=args,
    )

    return code


def raw_request(flow):
    data = netlib.http.http1.assemble_request(flow.request)
    return data

@@ -11,27 +11,8 @@
 lib%0A
-import netlib.http%0A
 from
@@ -34,16 +34,363 @@
 t dedent
+%0A%0Aimport netlib.http%0Afrom . import contentviews%0A%0A%0Adef prettify(data, headers=None):%0A    if not headers:%0A        return data%0A%0A    cv = contentviews.get_content_view(%0A        contentviews.get(%22Auto%22),%0A        data,%0A        headers=headers,%0A    )%0A%0A    if cv%5B0%5D == %22JSON%22:%0A        return %22%5Cn%22.join(l%5B0%5D%5B1%5D for l in cv%5B1%5D)%0A    else:%0A        return data
 %0A%0A%0Adef c
@@ -1813,24 +1813,33 @@
 '%25s'''%5Cn%22 %25 
+prettify(
 flow.request
@@ -1843,16 +1843,39 @@
 est.body
+, flow.request.headers)
 %0A       

Indent JSON body while exporting it as code