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':  {
                    'point': {
                        'events': { 'click': 'url'}
                    }
                } or None
        },
        'series': series
    }

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

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_run_id = itemgetter(1)
by_duration = itemgetter(2)

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

series = []
subsuites = []
for name, runid_dur in groupby(triplets, by_name):
    suiteName = ';'.join(name)
    s = [ {'x':testrun_vs_lastmodified[run_id], 'y':sum(map(by_duration, durs)), 'params': {'prefix': suiteName + ';', 'startDate': startDate.getTime(), 'endDate': endDate.getTime()}} for run_id, durs in groupby(runid_dur, by_run_id) ]
    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)
