# Path: bot/games/models.py
# class Game(models.Model):
#     name = models.CharField(_('name'), max_length=255)
#     alias_for = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE)
# 
#     objects = GameQuerySet.as_manager()
# 
#     class Meta:
#         verbose_name = _('game')
#         verbose_name_plural = _('games')
# 
#     def __str__(self):
#         return self.name
# 
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self._old_alias_for_id = self.alias_for_id
# 
#     def clean(self):
#         if self.alias_for and self.alias_for.alias_for:
#             raise ValidationError(_("Aliases can only span one level"))
#         if self.alias_for and self.alias_for.name == self.name:
#             raise ValidationError(_("An alias must have a different name"))
# 
# Path: bot/users/models.py
# class Member(models.Model):
#     discord_id = models.CharField(max_length=50, unique=True)
#     name = models.CharField(_('name'), max_length=255)
#     last_seen = models.DateTimeField(null=True, blank=True)
# 
#     is_bot = models.BooleanField(default=False)
#     can_admin_bot = models.BooleanField(default=False)
# 
#     objects = MemberQuerySet.as_manager()
# 
#     def __str__(self):
#         return '<@{} name={}>'.format(self.discord_id, self.name)


from typing import Union
from django.db import models
from django.db.models import Count, Sum
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from bot.games.models import Game
from bot.users.models import Member
import discord


class GameSessionQuerySet(models.QuerySet):

    def get_game_durations(self, member_id: str = None) -> models.QuerySet:
        base = self.filter(duration__isnull=False).values('game__name')
        annotations, extra_filters = dict(time=Sum('duration')), {}

        if not member_id:
            annotations['num_players'] = Count('member', distinct=True)
            extra_filters['num_players__gt'] = 1
        else:
            base = base.filter(member__discord_id=member_id)

        return (
            base
            .annotate(**annotations)
            .filter(**extra_filters)
            .order_by('-time')
        )

    def start(self, game: discord.Game, member: Member, server: str) -> models.Model:
        game = Game.objects.get_by_name(game.name)
        return self.create(
            server=server,
            member=member,
            game=game,
            start=timezone.now()
        )


# Path: bot/games/models.py
# class Game(models.Model):
#     name = models.CharField(_('name'), max_length=255)
#     alias_for = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE)
# 
#     objects = GameQuerySet.as_manager()
# 
#     class Meta:
#         verbose_name = _('game')
#         verbose_name_plural = _('games')
# 
#     def __str__(self):
#         return self.name
# 
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self._old_alias_for_id = self.alias_for_id
# 
#     def clean(self):
#         if self.alias_for and self.alias_for.alias_for:
#             raise ValidationError(_("Aliases can only span one level"))
#         if self.alias_for and self.alias_for.name == self.name:
#             raise ValidationError(_("An alias must have a different name"))
# 
# Path: bot/users/models.py
# class Member(models.Model):
#     discord_id = models.CharField(max_length=50, unique=True)
#     name = models.CharField(_('name'), max_length=255)
#     last_seen = models.DateTimeField(null=True, blank=True)
# 
#     is_bot = models.BooleanField(default=False)
#     can_admin_bot = models.BooleanField(default=False)
# 
#     objects = MemberQuerySet.as_manager()
# 
#     def __str__(self):
#         return '<@{} name={}>'.format(self.discord_id, self.name)


# Path: bot/plugins/stats/models.py
from typing import Union
from django.db import models
from django.db.models import Count, Sum
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from bot.games.models import Game
from bot.users.models import Member
import discord



class GameSessionQuerySet(models.QuerySet):

    def get_game_durations(self, member_id: str = None) -> models.QuerySet:
        base = self.filter(duration__isnull=False).values('game__name')
        annotations, extra_filters = dict(time=Sum('duration')), {}

        if not member_id:
            annotations['num_players'] = Count('member', distinct=True)
            extra_filters['num_players__gt'] = 1
        else:
            base = base.filter(member__discord_id=member_id)

        return (
            base
            .annotate(**annotations)
            .filter(**extra_filters)
            .order_by('-time')
        )

    def start(self, game: discord.Game, member: Member, server: str) -> models.Model:
        game = Game.objects.get_by_name(game.name)
        return self.create(
            server=server,
            member=member,
            game=game,
            start=timezone.now()
        )


    def last_session_for_member(self, member: Member, server: str) -> Union[None, models.Model]: