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

import java.util.Date as Date
import java.util.TimeZone as TimeZone
import java.util.Collections as Collections
import java.text.SimpleDateFormat as SimpleDateFormat
from modules.flakiness import Flakiness

paramDate = queryParameters.get('date')
paramRange = queryParameters.get('range')

def flakiness():
    queryParameters['testsToShow'] = 4

    flakiness = Flakiness(testRun, testRuns, queryParameters, startDate, endDate, tags)
    flakiness_result = flakiness.getFlakinessResult()
    print "flakiness_result ", flakiness_result
    flakiness_result['dates'] = flakiness_result['dates'][0:10]
    for each_test in flakiness_result['tests']:
        each_test['results'] = each_test['results'][0:10]

    flakiness_result['url'] = '/testspecifications/' + testRun.testSpecificationName + '/report/xlt.FlakinessOverview'
    flakiness_result['params'] = [{'prefix': '', 'date': paramDate, 'range': paramRange}]
    return flakiness_result


def failures_guage():
    events = testRun.getEvents()

    # events = testRuns.testRun.getEvents()
    print "Number of events in testRun: ", events.size()
    passed_set = list()
    failed_set = list()
    prefix = queryParameters.get('prefix') or ''
    if events:
        for ev in events:
            if ev.type == 'functionalResult':
                if not ev.get('name').startswith(prefix):
                    continue
                result = ev.get('result')
                if result is None:
                    continue
                if result == 'PASSED':
                    passed_set.append(ev.get('name'))
                else:
                    failed_set.append(ev.get('name'))

    total_tests = len(passed_set) + len(failed_set)
    return {
        'chart': {
            'type': 'solidgauge',
            'margin': 0,
            'events': {
                'click': '/testspecifications/' + testRun.testSpecificationName + '/report/xlt.Details'
            }
        },

        'title': None,

        'pane': {
            'center': ['50%', '85%'],
            'size': '140%',
            'startAngle': -90,
            'endAngle': 90,
            'background': {
                'backgroundColor': '#9ADA7F',
                'innerRadius': '60%',
                'outerRadius': '100%',
                'shape': 'arc',
                'borderColor': 'transparent'
            }
        },

        'tooltip': {
            'enabled': False
        },

        # the value axis
        'yAxis': {
            'stops': [
                [1.0, '#fd8d10']  # yellow
            ],
            'lineWidth': 0,
            'minorTickInterval': None,
            'tickPixelInterval': total_tests,
            'tickWidth': 0,
            'labels': {
                'enabled': False
            },
            'min': 0,
            'max': total_tests,
        },

        'plotOptions': {
            'solidgauge': {
                'dataLabels': {
                    'y': 4,
                    'borderWidth': 0,
                    'useHTML': True,
                    'format': '<div class="text-center">{y}<br/>' +
                              'of ' + str(total_tests) + '<br/>' +
                              'failed</div>',
                    'style': {
                        'fontWeight': 'normal',
                        'fontSize': '10px',
                        # 'color': '#606060',
                        'textAlign': 'center'
                    }
                }
            }
        },

        'series': [{
                     'name': 'Failures',
                     'data': [len(failed_set)]
                 }]
    }


def duration_trend(runs):
    durations = []
    run_times = []

    prefix = queryParameters.get('prefix') or ''

    for r in runs:
        duration = 0
        prefixEvents = testRuns.getEventsForRunIdWithPrefix(r.testRunId, prefix, { 'tags': tags })
        for event in (e for e in prefixEvents if e.type == 'functionalResult'):
            duration += event.get("duration") or 0
            if prefix == '':
                prefix = event.get('name').split(';')[0] + ";"

        durations.append({'y': duration / 1000.0, 'params': { 'prefix': prefix } })

    Collections.reverse(durations)
    Collections.reverse(run_times)
    
    return {
        'chart': {
            'events': {
                'click': { 'url': '/testspecifications/' + testRun.testSpecificationName + '/report/xlt.Durations', 'params': { 'prefix': prefix } }
            }
        },
        'credits': {
            'enabled': False
        },
        'colors': ['#ABD718', '#D31155', '#055F75', '#E36C16', '#009190'],
        'tooltip': {
            'pointFormat': '{series.name}: <b>{point.y}</b>'
        },
        'labels': {
            'enabled': False
        },
        'legend': {
            'enabled': False
        },
        'xAxis': {
            'title': None,
            'labels': {'enabled': False},
            'categories': run_times,
            'tickWidth': 0
        },
        'yAxis': {
            'labels': {
                'format': '{value} s',
            },
            'title': None,
            # 'min': 0
        },
        'plotOptions': {
            'series':  {
           } or None
        },
        'series': [{
            'data': durations,
            'name': 'duration',
            'tooltip': {
                'valueSuffix': ' s'
            },
        }]
    }


run_id = str(testRun.getId())
testRun
all_runs = []
all_runs.extend(testRuns.getTestRunsBetween(testRun.testSpecificationName, startDate.getTime(), endDate.getTime()))

resultHolder.setResult(
    {
        'flakiness': flakiness(),
        'duration': duration_trend(all_runs),
        'failures': failures_guage(),
        'title': 'Test health barometer'
    }
)