#!/usr/bin/python
#
# Format a result
#

import json
import jsontemplate
import pscheduler
import sys

from validate import result_is_valid

try:
   format = sys.argv[1]
except IndexError:
   format = 'text/plain'

input = pscheduler.json_load(exit_on_error=True)

valid, message = result_is_valid(input["result"])

if not valid:
    pscheduler.fail(message)

result = input["result"]
spec = input["spec"]

if format == 'text/plain':
    print 'Response Time: %s\n' % result['time']
    print 'Status Code: %s\n' % result['status'] 
    try:
        str = spec['parse']
        print 'String found: %s\n' % result['found']
    except KeyError:
        pass

elif format == 'text/html':
    print '<table>'
    print '    <tr>' 
    print '        <th>Response Time</th>'
    print '    </tr>'
    print '    <tr>'
    print '        <td>%s</td>' % result['time']
    print '    </tr>'
    print '    <tr>'
    print '        <th>Status Code</th>'
    print '    </tr>'
    print '    <tr>'
    print '        <td>%s</td>' % result['status']
    print '    </tr>'
    try:
        str = spec['parse']
        print '    <tr>'
        print '        <th>String found:</th>'
        print '    </tr>'
        print '    <tr>'
        print '         <td>%s</td>' % result['found']
        print '    </tr>' 
    except KeyError:
        pass
    print '</table>'

else:
   pscheduler.fail("Unsupported format '%s'" % format)
