from django.contrib import admin

from sports.models import (
    League,
    Player,
    Round,
    Season,
    Sport,
    SportEvent,
    Team,
)

from scrobbles.admin import ScrobbleInline


@admin.register(Sport)
class SportAdmin(admin.ModelAdmin):
    date_hierarchy = "created"
    ordering = ("name",)


@admin.register(League)
class LeagueAdmin(admin.ModelAdmin):
    date_hierarchy = "created"
    list_display = ("name", "abbreviation_str")
    raw_id_fields = ("sport",)
    ordering = ("name",)


@admin.register(Player)
class PlayerAdmin(admin.ModelAdmin):
    date_hierarchy = "created"
    list_display = ("name", "league", "team")
    raw_id_fields = ("league", "team")
    ordering = ("name",)


@admin.register(Season)
class SeasonAdmin(admin.ModelAdmin):
    date_hierarchy = "created"
    list_display = ("name", "league")
    raw_id_fields = ("league",)
    ordering = ("name",)


@admin.register(Round)
class RoundAdmin(admin.ModelAdmin):
    date_hierarchy = "created"
    list_display = ("name", "season")
    raw_id_fields = ("season",)
    ordering = ("name",)


@admin.register(Team)
class TeamAdmin(admin.ModelAdmin):
    date_hierarchy = "created"
    list_display = ("name", "league")
    raw_id_fields = ("league",)
    ordering = ("name",)


@admin.register(SportEvent)
class SportEventAdmin(admin.ModelAdmin):
    date_hierarchy = "created"
    list_display = (
        "title",
        "league",
        "event_type",
        "comp_str",
    )
    raw_id_fields = ("league", "teams", "players", "round")
    list_filter = ("league", "event_type")
    ordering = ("-created",)
    inlines = [
        ScrobbleInline,
    ]

    def comp_str(self, obj):
        teams = list(obj.teams.all())
        if len(teams) >= 2:
            return f"{teams[1]} v {teams[0]}"

        players = list(obj.players.all())
        if len(players) >= 2:
            return f"{players[0]} v {players[1]}"

        if len(players) == 1:
            return str(players[0])

        if len(teams) == 1:
            return str(teams[0])
