from django.db.models import Q

# Create your views here.
from rest_framework.decorators import api_view
from rest_framework.response import Response

from email_statistics_calculator.views import count_average_correctness, count_average_duration
from emails.models import Emails
from emails.serializers import EmailSerializer
from gamerun_manager.views import check_answer_correctness
from gameruns.models import EmailGameRuns, GameRuns


@api_view(('GET',))
def get_gamerun_summary(request):
    """
        Calculates summary for every email in current gamerun:
         * average answer correctness
         * average answer durations
         * player's answer duration

        :param request: http request
        :returns: array of emails and theirs statistics
    """
    gamerun_id = request.session['gamerun']
    gamerun = GameRuns.objects.filter(id__exact=gamerun_id).first()
    emails = gamerun.emails
    statistics = []

    for email in emails.iterator():
        average_correctness = count_average_correctness(email)
        average_duration = count_average_duration(email)
        players_duration = get_players_answer_duration(gamerun, email)
        answer = check_answer_correctness(gamerun, email)

        statistics.append({'email': EmailSerializer(email).data, 'average_correctness': average_correctness,
                           'average_duration': average_duration, 'players_duration': players_duration,
                           'answer': answer
                           })

    return Response(statistics)


def get_players_answer_duration(gamerun: GameRuns, email: Emails):
    """
        Gets **answer duration** of the given email in the gamerun

        :param gamerun: gamerun object
        :param email: email object
        :returns: player's answer duration for given email
    """
    duration = EmailGameRuns.objects.get(
        Q(email_id=email.id) & Q(game_run_id=gamerun.id) & ~Q(player_answer=None)).duration

    return str(duration).split('.')[0]
