import json
import urllib
from textwrap import dedent

import netlib.http
from netlib.utils import parse_content_type


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:
        if is_json(flow.request.headers):
            data = json.dumps(json.loads(flow.request.body), indent=4)
            data = "\njson = %s\n" % data
            args += "\n    json=json,"
        else:
            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


def is_json(headers):
    if headers:
        ct = parse_content_type(headers.get("content-type", ""))
        return ct and "%s/%s" % (ct[0], ct[1]) == "application/json"
    return False

@@ -1515,18 +1515,26 @@
         
-if
+json_obj =
  is_json
@@ -1550,25 +1550,64 @@
 uest.headers
-)
+, flow.request.body)%0A        if json_obj
 :%0A          
@@ -1634,33 +1634,12 @@
 json
-.loads(flow.request.body)
+_obj
 , in
@@ -2150,19 +2150,28 @@
 (headers
+, content
 ):%0A
-
     if h
@@ -2251,22 +2251,18 @@
         
-return
+if
  ct and 
@@ -2307,16 +2307,137 @@
 on/json%22
+:%0A            try:%0A                return json.loads(content)%0A            except ValueError:%0A                return False
 %0A    ret

Handle the case of correct json content-type but malformed body