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


def flakiness(runs):
    runs = runs[0:10]
    startDate = testRuns.makeStartDateIfProvided(str(runs[-1].getStartTime().getTime()))
    endDate = testRuns.makeEndDateIfProvided(None)
    prefix = queryParameters.get('prefix') or ''
    queryParameters['testsToShow'] = 4

    flakiness = Flakiness(testRun, testRuns, queryParameters, startDate, endDate)
    flakiness_result = flakiness.getFlakinessResult()
    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'] = '/reports/' + run_id + '/Configuration/Reports/Flakiness Overview'
    flakiness_result['params'] = [{'prefix': prefix, 'startDate': startDate.getTime(), 'endDate': endDate.getTime()}]
    return flakiness_result


def failures_guage():
    events = testRun.getEvents()
    passed_set = set()
    failed_set = set()
    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.add(ev.get('name'))
                else:
                    failed_set.add(ev.get('name'))

    total_tests = len(passed_set) + len(failed_set)
    return {
        'chart': {
            'type': 'solidgauge',
            'margin': 0,
            'events': {
                'click': '/reports/' + run_id + '/Configuration/Reports/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': '12px',
                        'color': '#333333',
                        'textAlign': 'center'
                    }
                }
            }
        },

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


def duration_trend(runs):
    durations = []
    run_times = []
    sdf = SimpleDateFormat("dd-MMM HH:mm:ss")

    start_date = runs[-1].getStartTime().getTime()
    end_date = runs[0].getStartTime().getTime()

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

    for r in runs:
        duration = 0
        prefixEvents = r.getEventsWithPrefix(prefix)
        for event in (e for e in prefixEvents if e.type == 'functionalResult'):
            duration += event.get("duration") or 0
        durations.append({'y': duration / 1000.0, 'params': { 'prefix': prefix, 'startDate': start_date, 'endDate': end_date} })

    Collections.reverse(durations)
    Collections.reverse(run_times)
    
    return {
        'chart': {
            'events': {
                'click': 'reports/' + run_id + '/Configuration/Reports/Durations'
            }
        },
        '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())
all_runs = [testRun]
all_runs.extend(testRuns.getPreviousRuns(testRun, 15))

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