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

from itertools import groupby
from operator import itemgetter

def duration_trend(series):
    return {
        'chart': {
        },
        'credits': {
            'enabled': False
        },
        'colors': ['#FFA500', '#69B749', '#4AA0C8', '#FCD364', '#8E2800', '#B85C5A', '#644D52', '#BEEB9F', '#7E827A', '#468966', '#F77A52', '#35203B', '#88A825', '#FF6F69', '#445878', '#FFE11A', '#FF8598', '#7E8AA2', '#45BF55', '#7FB2F0'],
        'tooltip': {
            'pointFormat': '{series.name}: <b>{point.y}</b>'
        },
        'labels': {
            'enabled': False
        },
        'legend': {
            'enabled': False
        },
        'xAxis': {
            'type': 'datetime',
            'title': None
        },
        'yAxis': {
            'labels': {
                'format': '{value} ms',
            },
            'title': None,
        }, 
        'plotOptions': {
                'series':  {
                    'marker':{'symbol': 'circle'},
                    'point': {
                        'events': { 'click': 'url'}
                    }
                } or None
        },
        'series': series
    }

title = self.getProperty('title')
maxRunsInHistory = self.getProperty('maxRunsInHistory')
prefix = queryParameters.get('prefix') or ''

print "going to search for tags ", tags
found_import_events = testRuns.getEventsBetween(startDate.getTime(), endDate.getTime(), {'testSpecification': testRun.getTestSpecificationName(), 'type': 'importStarted'})
testrun_vs_lastmodified = {event.get('runId'):event.get('lastModified') for event in found_import_events}

level = len(prefix.split(';'))

by_name = itemgetter(0)
by_last_modified = itemgetter(1)
by_duration = itemgetter(2)

found_events = testRuns.getEventsBetween(startDate.getTime(), endDate.getTime(), {'testSpecification': testRun.getTestSpecificationName(), 'type': 'functionalResult', 'tags': tags})
triplets = [(tuple(event.get('name').split(';')[:level]), testrun_vs_lastmodified.get(event.get('runId')), event.get('duration')) for event in found_events if event.get('name').startswith(prefix)]

triplets.sort()

series = []
subsuites = []
for name, lastmod_dur in groupby(triplets, by_name):
    suiteName = ';'.join(name)
    s = [ {'x':lastModifiedTime, 'y':sum(map(by_duration, durs)), 'params': {'prefix': suiteName + ';'}} for lastModifiedTime, durs in groupby(lastmod_dur, by_last_modified) if lastModifiedTime ]
    series.append({'name': suiteName, 'data': s })
    subsuites.append(name[-1])

bottomRight = duration_trend(series)
parentSuite = prefix[:-1]
if parentSuite.rfind(';') > 0:
    parentSuite = parentSuite[parentSuite.rfind('.')+1:]
maxRunsInHistory = len(testrun_vs_lastmodified)

report = { 'title':title, 'parentSuite':parentSuite, 'maxRunsInHistory':maxRunsInHistory, 'bottomRight':bottomRight, 'subsuites':subsuites}

resultHolder.setResult(report)
