import http.client
import argparse
import sys
import requests

def content_type_to_caps(content_type):
    """
    Converts MIME-style raw audio content type specifier to GStreamer CAPS string
    """
    default_attributes= {"rate": 16000, "format" : "S16LE", "channels" : 1, "layout" : "interleaved"}
    media_type, _, attr_string = content_type.replace(";", ",").partition(",")
    if media_type in ["audio/x-raw", "audio/x-raw-int"]:
        media_type = "audio/x-raw"
        attributes = default_attributes
        for (key,_,value) in [p.partition("=") for p in attr_string.split(",")]:
            attributes[key.strip()] = value.strip()
        return "%s, %s" % (media_type, ", ".join(["%s=%s" % (key, value) for (key,value) in attributes.items()]))
    else:
        return content_type


parser = argparse.ArgumentParser(description='Command line client for Aditu Live HTTP Post API')
parser.add_argument('-u', '--uri', default="https://live.aditu.eus", dest="uri", help="Server URI")
parser.add_argument('-l', '--language', default="eu", dest="language", help="Server URI")
parser.add_argument('--content-type', default='audio/x-raw-int; rate=16000', help="Use the specified content type (default for raw files)")
parser.add_argument('-i', '--api-id', default="", dest="api_id", help="API id")
parser.add_argument('-k', '--api-key', default="", dest="api_key", help="API key")
parser.add_argument('-s', '--chunk-size', default="0", dest="chunk_size", help="Chunk size")
parser.add_argument('--punctuate-case', default='false', help="Punctuate and put case")
parser.add_argument('--unexpand', default='false', help="Unexpand numbers, accronyms, abbreviations, etc.")
parser.add_argument('--save', default='false', help="Save the audio in user's file list")
parser.add_argument('audiofile', help="Audio file to be sent to the server", type=argparse.FileType('rb'), default=sys.stdin)
args = parser.parse_args()


prefix=args.uri[:args.uri.find(':')]
uri=args.uri[args.uri.find(':')+3:]
url = "/"+args.language+"/client/http/recognize"

data=args.audiofile.read()
all=data

post_url=prefix+'://'+uri+url
headers={
        'Content-Type': content_type_to_caps(args.content_type),
        'punctuationcase': args.punctuate_case,
        'unexpand': args.unexpand,
        'save': args.save,
        'api_id': args.api_id,
        'api_key': args.api_key
}
resp=requests.post(url=post_url,data=all,headers=headers)
print(resp.status_code)
print(resp.json())
