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

import re

def nameStartsWithPrefix(prefix, ev):
    if prefix is None or prefix == '':
        return True
    name = ev.get('name')
    return name.startswith(prefix)

def nextWordAfterPrefix(prefix, name):
    return re.split(';', name[len(prefix):])[0] or ''

def countLevel(prefix):
    return len(prefix.split(';')) - 1

events = testRuns.getEventsForRunId(testRun.testRunId, {'tags': tags})

rotation = -45

passed = {}
failed = {}
prefix = queryParameters.get('prefix') or ''
for ev in events:
    if ev.type == 'functionalResult' and nameStartsWithPrefix(prefix, ev):
        x = nextWordAfterPrefix(prefix, ev.get('name'))
        result = ev.get('result')
        if x is None:
            continue
        if result == 'PASSED':
            passed[x] = passed.get(x, 0) + 1
        else:
            failed[x] = failed.get(x, 0) + 1

categories = sorted(set(failed.keys() + passed.keys()))

def make_column_values(counts):
    return map(lambda t: counts.get(t, 0) > 1 and { 'y': counts[t], 'params': { 'prefix': '%s%s;' % (prefix, t) } } or counts.get(t, 0), categories)

# Rework our data for representation (to highcharts format)
passed = make_column_values(passed)
failed = make_column_values(failed)
#categories = map(lambda x: x[:20], categories)

level = countLevel(prefix)
if level == 0:
    title = 'Overview of test results'
else:
    title = 'Overview of test results at level %s' % level

resultHolder.setResult(
    {
        'chart': {
            'type': 'column'
        },
        'title': title,
        'xAxis': {
            'categories': categories,
            'labels': {
                'rotation': rotation,
            }
        },
        'yAxis': {
            'min': 0,
            'title': {
                'text': 'Number of tests',
                'style': {
                    'color': '#666',
                    'font-weight': 'normal'
                }
            },
            'minTickInterval': 1
        },
        'legend': {
            'borderColor': None,
            'symbolHeight': 16,
            'symbolWidth': 16
        },
        'plotOptions': {
            'column': {
                'animation': False,
                'cursor': 'pointer',
                'borderRadius': 2,
                'groupPadding': 0.1,
                'pointPadding': 0.01
            },
            'series':  {
                'point': {
                    'events': {
                        'click': 'url'
                    }
                }
            } or None
        },
        'series': [{
            'name': 'Passed',
            'data': passed
        }, {
            'name': 'Failed',
            'data': failed
        }]
    })

