#!/usr/bin/env python

import json

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

script = Script(description='List only entries matching given JSON paths in result')
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('urls', nargs='*', help='URLs to match')
script.add_argument('matches',nargs='*',help='Dot separated match paths to show')
args = script.parse_args()

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

def match_record(record,matches):
    results = []
    return results

for url in args.urls:
    script.log.debug('Submitting GET request to {0}'.format(url))

    try:
        res = request.get(url)
    except JSONRequestError as e:
        script.exit(1,emsg)

    res_text = response_code_text(res.status_code)
    if res_text != 'OK':
        script.error('RESPONSE CODE: {0}'.format(res_text))
        script.error('ERROR requesting 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)
        continue

    if args.debug:
        script.error('RESPONSE CODE: {0}'.format(res_text))

    if res.content.strip():
        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)

