from collections import defaultdict

from django import views
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404

from app.forms import RegisterForm
from app.models import EventResult, UserProfile


class IndexView(views.generic.TemplateView):
    template_name = 'index.djhtml'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # maps players to dicts of medal counts
        medals = defaultdict(lambda: defaultdict(int))

        for result in EventResult.objects.all():
            medals[result.participant][result.medal] += 1
        # maps players to score value
        scores = {}
        for player, medal_counts in medals.items():
            gold = medal_counts.get('gold', 0)
            silver = medal_counts.get('silver', 0)
            bronze = medal_counts.get('bronze', 0)
            scores[player] = gold * 5 + silver * 3 + bronze

        medals = sorted(medals.items(),
                        reverse=True,
                        key=lambda m: scores[m[0]])

        leaderboard = [{
            'participant': k,
            'profile': UserProfile.objects.get(user=k),
            'medal_counts': v,
            'score': scores[k]
        } for k, v in medals]

        context.update({
            'leaderboard': leaderboard,
            'medal_types': [t[0] for t in EventResult.MEDAL_TYPES],
        })

        return context


class RegisterView(views.generic.FormView):
    template_name = 'register.djhtml'
    form_class = RegisterForm
    success_url = '/'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'icons': list(range(0, UserProfile.NUM_PLAYER_ICONS)),
        })
        return context

    def form_valid(self, form):
        user = User.objects.create_user(form.cleaned_data['username'],
                                        form.cleaned_data['email'],
                                        form.cleaned_data['password'])

        user.userprofile.icon = form.cleaned_data['icon']
        user.save()

        login(self.request, user)
        return super().form_valid(form)


class UserProfileView(views.generic.DetailView):
    template_name = 'user-profile.djhtml'
    model = User
    context_object_name = 'profile_user'

    def get_object(self):
        return get_object_or_404(User, username=self.kwargs['username'])

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'profile': UserProfile.objects.get(user=self.object),
            'event_results': EventResult.objects.filter(
                participant=self.object),
        })
        return context
