
import re

def nameStartsWithPrefix(prefix, ev):
    if prefix is None or prefix == '':
        return True
    name = ev.get('name')
    return re.match('^' + re.escape(prefix[:-1]) + '\W', name)

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

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

events = testRun.getEvents()
# we now have all events of the superset. These contain references to other runs (of the children)
child_run_ids = []
for ev in events:
    if ev.type == 'execution':
        child_run_ids.append(ev.get('child_run_id'))
print 'I found', str(len(child_run_ids)), 'child run ids:', child_run_ids
events = []
for child_run_id in child_run_ids:
    child_run = testRuns.getTestRun(child_run_id)
    child_events = child_run.getEvents()
    print 'Looking at run', child_run_id, 'I found', str(len(child_events)), 'events'
    events.extend(child_events)

rotation = -45

if events:
    passed = {}
    failed = {}
    prefix = queryParameters['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 = countSemicolons(prefix)
    if level == 0:
        title = 'Test result overview'
    else:
        title = 'Test result overview at level %s' % level

    resultHolder.setResult(
        {
            'chart': {
                'type': 'column'
            },
            'title': {
                'text': 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
            }]
        })

