# 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 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

id = testRun.getTestRunId()
oldTestRuns = testRuns.getPreviousRuns(testRun, 2)
if (oldTestRuns.size() != 0):
    oldTestRun = oldTestRuns.get(0)
    oldEvents = oldTestRun.getEvents()
else:
    oldTestRun = None
    oldEvents = None
events = testRun.getEvents()

rotation = -45

# Figure out the new failures and passes
events_map = {}
if events and oldEvents:
    for ev in events:
        if ev.hasProperty('name'):
            events_map[ev.get('name')] = ev

oldEvents_map = {}
if oldEvents:
    for ev in oldEvents:
        if ev.hasProperty('name'):
            oldEvents_map[ev.get('name')] = ev

deltaEvents = []
for name in events_map.keys():
    if oldEvents_map.has_key(name) == False:
        deltaEvents.append(events_map[name])
    else:
        if events_map[name].get('result') != oldEvents_map[name].get('result'):
            deltaEvents.append(events_map[name])

# Chart JSON generation
if deltaEvents:
    passed = {}
    failed = {}
    prefix = queryParameters.get('prefix') or ''
    for ev in deltaEvents:
        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)

    passed = make_column_values(passed)
    failed = make_column_values(failed)
    #xs = map(lambda x: x[:20], xs)
    
    level = countSemicolons(prefix)
    if level == 0:
        title = 'Diff Bar chart'
    else:
        title = 'Diff Bar chart 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
            }]
        })


