# Copyright (C) 2020 by Animath
# SPDX-License-Identifier: GPL-3.0-or-later

from django.conf import settings
from django.contrib import admin
from django.http import HttpRequest
from django.utils.translation import gettext_lazy as _

from .models import Note, Participation, Passage, Pool, Solution, Team, Tournament, Tweak, WrittenReview


class ParticipationInline(admin.StackedInline):
    model = Participation
    extra = 0
    autocomplete_fields = ('team', 'tournament',)
    show_change_link = True


class ParticipationTabularInline(admin.TabularInline):
    model = Participation
    extra = 0
    fields = ('team', 'valid', 'final',)
    readonly_fields = ('team',)
    ordering = ('final', 'valid', 'team__trigram',)
    autocomplete_fields = ('tournament',)
    show_change_link = True


class SolutionInline(admin.TabularInline):
    model = Solution
    extra = 0
    ordering = ('problem',)
    autocomplete_fields = ('participation',)
    show_change_link = True


class WrittenReviewInline(admin.TabularInline):
    model = WrittenReview
    extra = 0
    ordering = ('passage__solution_number', 'type',)
    autocomplete_fields = ('passage',)
    show_change_link = True


class PoolInline(admin.TabularInline):
    model = Pool
    extra = 0
    autocomplete_fields = ('tournament', 'participations', 'jury_president', 'juries',)
    show_change_link = True


class PassageInline(admin.TabularInline):
    model = Passage
    extra = 0
    ordering = ('position',)
    show_change_link = True

    def get_autocomplete_fields(self, request: HttpRequest) -> tuple[str]:
        fields = ('reporter', 'opponent', 'reviewer',)
        if settings.HAS_OBSERVER:
            fields += ('observer',)
        return fields


class NoteInline(admin.TabularInline):
    model = Note
    extra = 0
    autocomplete_fields = ('jury',)
    show_change_link = True


class TweakInline(admin.TabularInline):
    model = Tweak
    extra = 0
    autocomplete_fields = ('participation', 'pool',)
    show_change_link = True


@admin.register(Team)
class TeamAdmin(admin.ModelAdmin):
    list_display = ('name', 'trigram', 'tournament', 'valid', 'final',)
    search_fields = ('name', 'trigram',)
    list_filter = ('participation__valid', 'participation__tournament', 'participation__final',)
    inlines = (ParticipationInline,)

    @admin.display(description=_("tournament"))
    def tournament(self, record):
        return record.participation.tournament

    @admin.display(description=_("valid"), boolean=True)
    def valid(self, team):
        return team.participation.valid

    @admin.display(description=_("selected for final"), boolean=True)
    def final(self, team):
        return team.participation.final


@admin.register(Participation)
class ParticipationAdmin(admin.ModelAdmin):
    list_display = ('team', 'tournament', 'valid', 'final',)
    search_fields = ('team__name', 'team__trigram',)
    list_filter = ('valid', 'tournament',)
    autocomplete_fields = ('team', 'tournament',)
    inlines = (SolutionInline, WrittenReviewInline,)


@admin.register(Pool)
class PoolAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'tournament', 'round', 'letter', 'room', 'teams', 'jury_president',)
    list_filter = ('tournament', 'round', 'letter', 'room',)
    search_fields = ('participations__team__name', 'participations__team__trigram',)
    autocomplete_fields = ('tournament', 'participations', 'jury_president', 'juries',)
    inlines = (PassageInline, TweakInline,)

    @admin.display(description=_("teams"))
    def teams(self, record: Pool):
        return ', '.join(p.team.trigram for p in record.participations.all())


@admin.register(Passage)
class PassageAdmin(admin.ModelAdmin):
    list_filter = ('pool__tournament', 'pool__round', 'pool__letter', 'solution_number',)
    search_fields = ('pool__participations__team__name', 'pool__participations__team__trigram',)
    ordering = ('pool__tournament', 'pool__round', 'pool__letter', 'position',)
    inlines = (NoteInline,)

    @admin.display(description=_("reporter"), ordering='reporter__team__trigram')
    def reporter_trigram(self, record: Passage):
        return record.reporter.team.trigram

    @admin.display(description=_("opponent"), ordering='opponent__team__trigram')
    def opponent_trigram(self, record: Passage):
        return record.opponent.team.trigram

    @admin.display(description=_("reviewer"), ordering='reviewer__team__trigram')
    def reviewer_trigram(self, record: Passage):
        return record.reviewer.team.trigram

    @admin.display(description=_("observer"), ordering='observer__team__trigram')
    def observer_trigram(self, record: Passage):
        return record.observer.team.trigram if record.observer else None

    @admin.display(description=_("pool"), ordering='pool__letter')
    def pool_abbr(self, record):
        return f"{record.pool.short_name}"

    @admin.display(description=_("tournament"), ordering='pool__tournament__name')
    def tournament(self, record: Passage):
        return record.pool.tournament

    def get_list_display(self, request: HttpRequest) -> tuple[str]:
        if settings.HAS_OBSERVER:
            return ('__str__', 'reporter_trigram', 'solution_number', 'opponent_trigram',
                    'reviewer_trigram', 'observer_trigram', 'pool_abbr', 'position', 'tournament')
        else:
            return ('__str__', 'reporter_trigram', 'solution_number', 'opponent_trigram',
                    'reviewer_trigram', 'pool_abbr', 'position', 'tournament')

    def get_autocomplete_fields(self, request: HttpRequest) -> tuple[str]:
        fields = ('pool', 'reporter', 'opponent', 'reviewer',)
        if settings.HAS_OBSERVER:
            fields += ('observer',)
        return fields


@admin.register(Note)
class NoteAdmin(admin.ModelAdmin):
    search_fields = ('jury__user__last_name', 'jury__user__first_name', 'passage__reporter__team__trigram',)
    autocomplete_fields = ('jury', 'passage',)

    @admin.display(description=_("pool"))
    def pool(self, record):
        return record.passage.pool.short_name

    def get_list_display(self, request: HttpRequest) -> tuple[str]:
        fields = ('passage', 'pool', 'jury', 'reporter_writing', 'reporter_oral',
                  'opponent_writing', 'opponent_oral', 'reviewer_writing', 'reviewer_oral',)
        if settings.HAS_OBSERVER:
            fields += ('observer_writing', 'observer_oral',)
        return fields

    def get_list_filter(self, request: HttpRequest) -> tuple[str]:
        fields = ('passage__pool__letter', 'passage__solution_number', 'jury',
                  'reporter_writing', 'reporter_oral', 'opponent_writing', 'opponent_oral',
                  'reviewer_writing', 'reviewer_oral',)
        if settings.HAS_OBSERVER:
            fields += ('observer_writing', 'observer_oral',)
        return fields


@admin.register(Solution)
class SolutionAdmin(admin.ModelAdmin):
    list_display = ('team', 'tournament', 'problem', 'final_solution',)
    list_filter = ('problem', 'participation__tournament', 'final_solution',)
    search_fields = ('participation__team__name', 'participation__team__trigram',)
    autocomplete_fields = ('participation',)

    @admin.display(ordering='participation__team', description=_("team"))
    def team(self, record):
        return record.participation.team

    @admin.display(ordering='participation__tournament__name', description=_("tournament"))
    def tournament(self, record):
        return Tournament.final_tournament() if record.final_solution else record.participation.tournament


@admin.register(WrittenReview)
class WrittenReviewAdmin(admin.ModelAdmin):
    list_display = ('participation', 'type', 'reporter', 'passage',)
    list_filter = ('participation__tournament', 'type', 'passage__solution_number',)
    search_fields = ('participation__team__name', 'participation__team__trigram',)
    autocomplete_fields = ('participation', 'passage',)

    @admin.display(description=_("reporter"))
    def reporter(self, record: WrittenReview):
        return record.passage.reporter

    @admin.display(description=_("problem"))
    def problem(self, record: WrittenReview):
        return record.passage.solution_number


@admin.register(Tournament)
class TournamentAdmin(admin.ModelAdmin):
    list_display = ('name', 'date_start', 'date_end',)
    search_fields = ('name',)
    ordering = ('date_start', 'name',)
    autocomplete_fields = ('organizers',)
    inlines = (ParticipationTabularInline, PoolInline,)


@admin.register(Tweak)
class TweakAdmin(admin.ModelAdmin):
    list_display = ('participation', 'pool', 'diff',)
    list_filter = ('pool__tournament', 'pool__round',)
    search_fields = ('participation__team__name', 'participation__team__trigram',)
    autocomplete_fields = ('participation', 'pool',)
