# -*- encoding: utf-8 -*-
from datetime import date

from django.contrib import auth
from django.core.urlresolvers import reverse
import django.forms
import django.http
from django.contrib.messages.views import SuccessMessageMixin
from django.utils.translation import gettext as _
from django.views import generic

from events.models import Event
from events.views import EventDetailMixin
from . import forms, models
from utils.mixins import LoginRequiredMixin, PermissionRequiredMixin

kyu_dan_order = {
    '+full_name': ('user__last_name', 'user__first_name'),
    '-full_name': ('-user__last_name', '-user__first_name'),
    '+hanchan_count': ('hanchan_count',),
    '-hanchan_count': ('-hanchan_count',),
    '+rank': ('-kyu', 'dan'),
    '-rank': ('-dan', 'kyu'),
    '+score': ('dan_points', 'kyu_points'),
    '-score': ('-dan_points', '-kyu_points'),
    '+username': ('user__username',),
    '-username': ('-user__username',)
}


class DeleteHanchan(EventDetailMixin, PermissionRequiredMixin, generic.DeleteView):
    """
    Fragt zuerst nach, ob die Hanchan wirklich gelöscht werden soll.
    Wir die Frage mit "Ja" beantwortet, wird die die Hanchan gelöscht.
    """
    form_class = forms.HanchanForm
    model = models.Hanchan
    permission_required = 'mahjong_ranking.delete_hanchan'
    pk_url_kwarg = 'hanchan'

    def get_success_url(self):
        return reverse('event-hanchan-list',
                       kwargs={'event': self.object.event.pk})


class HanchanForm(SuccessMessageMixin, EventDetailMixin, PermissionRequiredMixin, generic.UpdateView):
    """
    Ein Formular um neue Hanchans anzulegen, bzw. eine bestehende zu
    bearbeitsen
    """
    form_class = forms.HanchanForm
    model = models.Hanchan
    permission_required = 'mahjong_ranking.add_hanchan'

    def get_context_data(self, **kwargs):
        context = generic.UpdateView.get_context_data(self, **kwargs)
        context['event'] = self.event
        return context

    def get_form_class(self):
        """
        Users with edit Persmission will see the AdminForm to confirm
        unconfirmed Hanchans.
        """
        if self.request.user.has_perm('mahjong_ranking.change_hanchan'):
            return forms.HanchanAdminForm
        else:
            return forms.HanchanForm

    def get_object(self, queryset=None):
        if self.kwargs.get('hanchan') and self.request.user.has_perm('mahjong_ranking.change_hanchan'):
            hanchan = models.Hanchan.objects.get(id=self.kwargs['hanchan'])
            self.event = hanchan.event
        elif self.kwargs.get('event'):
            self.event = models.Event.objects.get(id=self.kwargs['event'])
            hanchan = models.Hanchan(
                event=self.event,
                start=self.event.start
            )
        return hanchan

    def get_success_url(self):
        """
        Adding a new Hanchan redirect to create_hanchan form.
        Editing an exiting one: redierect to the Hanchanevent.
        """
        if self.kwargs.get('hanchan'):
            return self.object.get_absolute_url()
        else:
            return reverse('add-hanchan-form', kwargs={'event': self.event.pk})

    def get_success_message(self, cleaned_data):
        if self.kwargs.get('hanchan'):
            return _('%s has been updated successfully.') % self.object
        else:
            return _('%s has been added successfully. You can now add a new one.') % self.object


class EventHanchanList(EventDetailMixin, generic.ListView):
    """
    Auflistung aller Hanchan die während der Veranstaltung gespielt wurden.
    """
    model = models.Hanchan
    template_name = 'mahjong_ranking/eventhanchan_list.html'

    def get_queryset(self):
        try:
            self.event = models.Event.objects.get(pk=self.kwargs['event'])
            queryset = models.Hanchan.objects.filter(event=self.event)
            queryset = queryset.order_by('start')
            return queryset
        except models.Event.DoesNotExist:
            raise django.http.Http404(_('Event does not exist'))


class EventRankingList(EventDetailMixin, generic.ListView):
    """
    Anzeige des Eventrankings, daß erstellt wurde falls der Termin als internes
    Turnier markiert wurde.
    """
    model = models.EventRanking

    def get_queryset(self):
        try:
            self.event = models.Event.objects.get(pk=self.kwargs['event'])
            queryset = models.EventRanking.objects.filter(event=self.event)
            return queryset.prefetch_related()
        except models.Event.DoesNotExist:
            raise django.http.Http404(_('Event does not exist'))


class KyuDanRankingList(generic.ListView):
    """
    Anzeige aller Spiele mit ihrem Kyu bzw Dan Grad.
    """
    default_order = '-score'
    order_by = ''
    paginate_by = 25

    def dispatch(self, request, *args, **kwargs):
        self.order_by = kyu_dan_order[
            kwargs.get('order_by', self.default_order)
        ]
        return generic.ListView.dispatch(self, request, *args, **kwargs)

    def get_queryset(self):
        queryset = models.KyuDanRanking.objects.all().order_by(*self.order_by)
        return queryset.select_related('user__membership')


class SeasonRankingList(generic.ListView):
    model = models.SeasonRanking
    paginate_by = 25
    season = None

    def get_queryset(self):
        self.season = int(self.kwargs.get('season', date.today().year))
        queryset = self.model.objects.filter(season=self.season,
                                             placement__isnull=False)
        return queryset.select_related()

    def get_context_data(self, **kwargs):
        context = super(SeasonRankingList, self).get_context_data(**kwargs)
        context['season'] = self.season
        context['season_start'] = date(year=self.season, month=1, day=1)
        context['season_end'] = date(year=self.season, month=12, day=31)
        context['season_list'] = models.SeasonRanking.objects.season_list
        context['latest_hanchan_list'] = models.Hanchan.objects.confirmed_hanchans()[:3]
        context['latest_event_list'] = Event.objects.archive()[:3]
        return context


class PlayerScore(LoginRequiredMixin, generic.ListView):
    paginate_by = 25

    def get(self, request, *args, **kwargs):
        user_model = auth.get_user_model()
        try:
            self.user = user_model.objects.get(username=self.kwargs.get('username'))
        except user_model.DoesNotExist:
            raise django.http.Http404(_("No user found matching the name {}").format(self.kwargs.get('username')))
        return super(PlayerScore, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = generic.ListView.get_context_data(self, **kwargs)
        context['membership'] = self.user
        try:
            context['kyu_dan_ranking'] = models.KyuDanRanking.objects.get(
                user=self.user)
        except models.KyuDanRanking.DoesNotExist:
            context['ranking'] = None
        try:
            context['ladder_ranking'] = models.SeasonRanking.objects.get(
                user=self.user,
                season=date.today().year)
        except models.SeasonRanking.DoesNotExist:
            context['ladder_ranking'] = models.SeasonRanking(user=self.user)
        return context


class PlayerDanScore(PlayerScore):
    template_name = 'mahjong_ranking/player_dan_score.html'

    def get_queryset(self):
        return models.Hanchan.objects.dan_hanchans(user=self.user)


class PlayerInvalidScore(PlayerScore):
    template_name = 'mahjong_ranking/player_invalid_score.html'

    def get_queryset(self):
        return models.Hanchan.objects.unconfirmed_hanchans(user=self.user)


class PlayerKyuScore(PlayerScore):
    template_name = 'mahjong_ranking/player_kyu_score.html'

    def get_queryset(self):
        return models.Hanchan.objects.kyu_hanchans(self.user)


class PlayerLadderScore(PlayerScore):
    template_name = 'mahjong_ranking/player_ladder_score.html'

    def get_context_data(self, **kwargs):
        context = super(PlayerLadderScore, self).get_context_data(**kwargs)
        context['season'] = self.season
        context['season_start'] = date(year=self.season, month=1, day=1)
        context['season_end'] = date(year=self.season, month=12, day=31)
        context['season_list'] = models.SeasonRanking.objects.season_list
        return context

    def get_queryset(self, **kwargs):
        try:
            self.season = int(self.request.GET.get('season'))
        except:
            self.season = date.today().year
        hanchan_list = models.Hanchan.objects.season_hanchans(user=self.user, season=self.season)
        print hanchan_list
        return hanchan_list
