""" Admin Interface to manipulate the maistar ranking """
from django.contrib import admin
from django.utils.translation import ugettext as _

from . import forms, models


def recalculate(modeladmin, request, queryset):
    """ Force an recalculation of the seleceted Ranking objects.

    :param modeladmin: The current ModelAdmin.
    :param request: An HttpRequest representing the current request.
    :param queryset: A QuerySet containing the objects selected by the user.
    """
    if isinstance(modeladmin, RankingAdmin):
        seasons = set()
        for ranking in queryset:
            ranking.recalculate()
            seasons.add(ranking.season)
        for season in seasons:
            models.Ranking.objects.calculate_rankings(season)


recalculate.short_description = _("Recalculate")


class RankingAdmin(admin.ModelAdmin):
    """Admin interface for Mai-Star season ladder ranking entries."""
    actions = [recalculate]
    list_display = (
        'season', 'placement', 'user', 'avg_placement', 'avg_score',
        'games_count', 'games_good', 'games_won'
    )
    list_display_links = ('user',)
    list_filter = ['season']


class GameAdmin(admin.ModelAdmin):
    """Admin interface to manage Mai-Star game scores."""
    actions = [recalculate]
    # date_hierarchy = 'event__start'
    fields = (
        'event',
        ('player1', 'player1_score', 'player1_placement'),
        ('player2', 'player2_score', 'player2_placement'),
        ('player3', 'player3_score', 'player3_placement'),
        ('player4', 'player4_score', 'player4_placement'),
        ('player5', 'player5_score', 'player5_placement'),
        ('player6', 'player6_score', 'player6_placement'),
        'comment',
        'confirmed'
    )
    form = forms.GameForm
    list_display = ('event', 'season', 'player_names', 'comment', 'confirmed')
    readonly_fields = (
        'player1_placement', 'player2_placement', 'player3_placement',
        'player4_placement', 'player5_placement', 'player6_placement'
    )
    search_fields = [
        'player1__username', 'player2__username', 'player3__username',
        'player4__username', 'player5__username', 'player6__username'
    ]


admin.site.register(models.Game, GameAdmin)
admin.site.register(models.Ranking, RankingAdmin)
