# NOTE: Please do not edit this file directly
# Create your custom reports in the 'ext' folder

from org.joda.time.format import DateTimeFormat

dateFormatter = DateTimeFormat.forStyle('SS')

if queryParameters.get('runId'):
    testRun = testRuns.getTestRun(queryParameters.get('runId'))

fields = set()

for ev in testRun.events:
    fields.update(ev.properties.keySet())

fields.difference_update(['testSpecification', 'tags', '_id', 'runId', 'timestamp', 'type'])

kinds = {
    'timestamp': 'date',
    'lastModified': 'date'
}

columns = ['timestamp', 'type'] + sorted(fields)

model = {
    'kind': [ kinds.get(col, col) for col in columns ],
    'body': [
        [ev.get(col) for col in columns ] for ev in testRun.events
    ]
}


def duration(milliseconds):
    seconds = milliseconds / 1000;
    minutes = seconds / 60;
    hours = minutes / 60;
    minutes = minutes % 60;
    seconds = seconds % 60;
    milliseconds = milliseconds % 1000;
    return (hours > 0 and ('%dh ' % hours) or '') + \
            (minutes > 0 and ('%sm ' % minutes) or '') + \
            (seconds > 0 and ('%ds ' % seconds) or '') + \
            '%sms' % milliseconds;


def render_cell(cell, kind):
    #if kind == 'qualification':
    #    return '<sprite img="testspecification_qualification" sprite-class="icon" class="test-specification-type %s"></sprite>' % (cell and 'finished' or 'failed',)
    if kind == 'date':
        return dateFormatter.print(cell)
    elif kind == 'duration':
        return cell and duration(cell) or ''
    else:
        return str(cell)


def render_row(row):
    kind = model['kind']
    return ''.join('<td>' + (cell is not None and render_cell(cell, kind[i]) or '') + '</td>' for i, cell in enumerate(row))

startDate = dateFormatter.print(testRun.startTime.time)

resultHolder.setResult(
    """
    <h2>Test run events for run <em>%s</em>, executed on <em>%s</em></h2>
    <table class="table">
    <thead>
    <tr>
    """ % (testRun.id, startDate) + \
    ''.join('<th>' + cell + '</th>' for cell in columns) + \
    """
    </tr>
    </thead>
    <tbody>
    """ + \
    ''.join('<tr>' + ''.join(render_row(row)) + '</tr>' for row in model['body']) + \
    """
    </tbody>
    </table>
    """)