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

from operator import itemgetter


def _get_result(r):
    return r == 'OK' or r == 'PASSED'

def duration_trend(series):
    return {
        'chart': {
            'type': 'line'
        },
        'credits': {
            'enabled': False
        },
        'colors': ['#FFA500'],
        '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':  {
                        'lineWidth': 2,
                        'allowPointSelect': True,
                       'marker':{'symbol': 'circle', 'radius': 6, 'states':{'select': {'fillColor':'#59AC39', 'lineWidth': 1, 'radius': 10}}},
                       'color': '#59AC39',
                       'point': {
                           'events': { 'click': "function () { }" }
                       }
                       } or None
        },
        'series': series
    }

test_specification = testRun.getTestSpecificationName()
test_case = queryParameters.get('testcase')

if self.hasProperty('extraPropertiesAsColumns'):
    extraPropertiesAsColumns = self.getProperty('extraPropertiesAsColumns')
else:
    extraPropertiesAsColumns = []

by_last_modified = itemgetter(1)

found_import_events = testRuns.getEventsBetween(startDate.getTime(), endDate.getTime(), {'testSpecification': test_specification, 'type': 'importStarted'})
print 'found_import_events', len(found_import_events)
testrun_vs_lastmodified = [(event.get('runId'), event.get('lastModified')) for event in found_import_events ]
sorted_testrun_vs_lastmodified = sorted(testrun_vs_lastmodified, key=by_last_modified)

by_run_id = itemgetter(0)
by_result = itemgetter(1)
by_event = itemgetter(2)

found_events = testRuns.getEventsBetween(startDate.getTime(), endDate.getTime(), {'testSpecification': test_specification, 'name':test_case, 'type': 'functionalResult', 'tags': tags})
print 'found_events', len(found_events)
run_vs_result = dict([(event.get('runId'), event) for event in found_events])
tests = []
series = []
data = []
for run_id, date in sorted_testrun_vs_lastmodified:
    result_event = run_vs_result.get(run_id)
    if(result_event is not None):
        details = {'date': date,
                   'eventId': result_event.getId(),
                   'result': _get_result(result_event.get('result')),
                   'duration': result_event.get('duration'),
                   'firstError': result_event.get('firstError') if result_event.hasProperty('firstError') else '',
                   'tags': result_event.get('tags')}
        for extraProp in extraPropertiesAsColumns:
            details[extraProp] = result_event.get(extraProp)
        tests.append(details)
        data.append({'x':date, 'y':result_event.get('duration')})

series.append({'name': test_case.split(';')[-1], 'data': data })
resultHolder.setResult({'title': 'Test case details for %s' % test_case.split(';')[-1], 'details': tests, 'chartData': duration_trend(series), 'extraPropertiesAsColumns': extraPropertiesAsColumns})
