#!/usr/bin/env python

import json
import sys
import os
import argparse

from jsontester.shell import Script
from jsontester.request import JSONRequest,JSONRequestError,response_code_text

script = Script(description='Send a HTTP POST request with data from file to given URL as JSON')
script.add_argument('-r','--raw',action='store_true',help='No output formatting')
script.add_argument('-i','--indent',type=int,default=2,help='Result indent level')
script.add_argument('-D','--data-from',type=argparse.FileType('r'),help='Data to send in POST request')
script.add_argument('urls', nargs='*', help='URLs to post')
args = script.parse_args()

request = JSONRequest(browser=args.browser, username=args.username, password=args.password, verify=args.insecure)

if not args.data_from:
    script.exit(1,'POST data to send is required argument')

elif args.data_from:
    script.log.debug('Reading POST data from file')
    try:
        post_data = args.data_from.read()
    except OSError as e:
        script.exit(1,'Error reading POST data from file {0}: {1}'.format(args.data, e))

else:
    script.exit(1,'Could not parse POST data from anywhere')

script.log.debug('POST {0} bytes:\n{1}'.format(len(post_data), post_data))
for url in args.urls:

    try:
        res = request.post(url,data=post_data)
    except JSONRequestError as e:
        script.exit(1, e)

    res_text = response_code_text(res.status_code)
    if res_text != 'CREATED':
        script.error('RESPONSE CODE: {0}\n'.format(res_text))
        script.message('ERROR adding JSON resource')
        if args.raw:
            script.error(res.content)
        else:
            try:
                script.error(json.dumps(json.loads(res.content),indent=args.indent))
            except ValueError:
                script.error(res.content)

    else:
        script.error('RESPONSE CODE: {0}\n'.format(res_text))
        if args.raw:
            script.message(res.content)
        else:
            try:
                script.message(json.dumps(json.loads(res.content),indent=args.indent))
            except ValueError:
                script.error(res.content)

