"""Views for the main app."""

from functools import reduce

from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.db.models import Q, Case, When, Value, IntegerField

from .models import Peg, Team, Member


def index(request):
    return render(request, 'index.html')

def results(request):
    return render(request, 'results.html')

def scoreboard(request):
    return render(request, 'scoreboard.html')

def teams(request):
    return render(request, 'teams.html')

def bulk_create_pegs(request):
    """Bulk create pegs"""

    number_of_pegs = request.POST.get("pegAmount")
    for i in range(int(number_of_pegs)):
        Peg.objects.create()

    # return to previous page
    return redirect(request.META.get('HTTP_REFERER'))

def get_teams(request):
    """Returns a JsonResponse containing a dictionary with a k/v pair for a list of teams.

    Args:
        request: the web request object.
    Returns:
        JsonResponse: dictionary of teams like so {'teams': [{}, {}, {}]}.
    """

    if not request.POST:
        return

    search = request.POST.get("search")
    sort_teams = request.POST.get("sortTeams") or "team_number"
    sort_members = request.POST.get("sortMembers") or "peg_number"

    teams = Team.objects.order_by(sort_teams).all()

    # Filter out teams that don't contain members being searched for
    if search:
        search_terms = search.split()
        members = Member.objects.filter(
            reduce(
                lambda x, y: x | y,
                [
                    Q(first_name__icontains=term) | Q(last_name__icontains=term)
                    for term in search_terms
                ]
            )
        )
        teams = teams.filter(members__in=members).distinct()

    # Create a dictionary for the data that is JSON safe
    response_data = {"teams": []}
    for team in teams:
        team_data = {
            "team_number": team.team_number,
            "section_letter": team.section_letter if team.section_letter else None,
            "members": [
                {
                    "first": member.first_name,
                    "last": member.last_name,
                    "id": member.id,
                    "team": team.team_number,
                    "peg": member.peg_number
                }
                for member in team.members.order_by(sort_members).all()
            ]
        }
        response_data["teams"].append(team_data)

    response_data["sortTeams"] = sort_teams
    response_data["sortMembers"] = sort_members

    return JsonResponse(response_data)

def update_member(request):
    """Update a member. Returns a JsonResponse with the updated teams."""

    if not request.POST:
        return

    # Get the updated values
    member_id = request.POST.get("memberId")
    first = request.POST.get("first")
    last = request.POST.get("last")
    team_number = request.POST.get("teamNumber")
    peg_number = request.POST.get("pegNumber")

    # Get the member and team
    member = Member.objects.get(id=member_id)
    team = Team.objects.get(team_number=team_number)

    # Update the member
    member.first_name = first
    member.last_name = last
    member.team = team
    member.peg_number = peg_number

    member.save()

    return get_teams(request)
