from __future__ import annotations
from os.path import splitext

from django.contrib.auth.models import User
from django.db.models import Q, Model, CASCADE, ForeignKey, ImageField
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver

from games.consumers import game_manager
from . import FriendModel


def upload_to(instance, filename: str):
    return f"./profiles/static/avatars/{instance.pk}{splitext(filename)[1]}"


class ProfileModel(Model):
    user = ForeignKey(User, on_delete=CASCADE)
    avatar = ImageField(upload_to=upload_to, default="./profiles/static/avatars/default.avif")

    def get_game(self) -> int:
        for game in game_manager._game_list:
            for player in game.get_players_connected():
                if (player.user_id == self.user.pk):
                    return game.game_id
        return None

    def get_friends(self) -> list[ProfileModel]:
        friends: list[ProfileModel] = []

        for friendship in FriendModel.FriendModel.objects.filter(Q(friend1=self) | Q(friend2=self)):
            friends.append(friendship.friend1 if friendship.friend1 != self else friendship.friend2)

        return friends

    def is_friend(self, friend):
        return friend in self.get_friends()

    def delete_friend(self, friend):
        print(friend)
        FriendModel.FriendModel.objects.get(
            (Q(friend1=self) & Q(friend2=friend)) |
            (Q(friend2=self) & Q(friend1=friend))
        ).delete()


@receiver(pre_delete, sender=ProfileModel)
def delete_profile_picture(sender, instance, **kwargs):
    if instance.avatar.name != './profiles/static/avatars/default.avif':
        instance.avatar.storage.delete(instance.avatar.name)


@receiver(post_save, sender=User)
def on_user_created(sender, instance, created, **kwargs):
    if created:
        profile: ProfileModel = ProfileModel.objects.create(pk=instance.pk, user=instance)
        profile.save()
