from django.db import models

from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from django.db.models import IntegerField

from games.consumers import game_manager

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

# Create your models here.
class ProfileModel(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    avatar = models.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

@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()
        
class BlockModel(models.Model):
    blocker = IntegerField(primary_key=False)
    blocked = IntegerField(primary_key=False)

    def __str__(self):
        return "blocker_id: " + str(self.blocker) + ", blocked_id: " + str(self.blocked)

class AskFriendModel(models.Model):
    asker = IntegerField(primary_key=False)
    asked = IntegerField(primary_key=False)

    def getAsked(self, asker):
        askeds = []

        for ask in AskFriendModel.objects.filter(asker=asker):
            askeds.append(ask.asked)

        return askeds

    def getAsker(self, asked):
        askers = []

        for ask in AskFriendModel.objects.filter(asked=asked):
            askers.append(ask.asker)

        return askers

    def deleteAsk(self, asker, asked):

        deleted = AskFriendModel.objects.filter(asker=asker, asked=asked)

        if (deleted.count() == 0 or not deleted):
            return False

        deleted.delete()
        return True

class FriendModel(models.Model):
    user_id1 = IntegerField(primary_key=False)
    user_id2 = IntegerField(primary_key=False)

    def getFriends(self, user_id):
        friends = []

        for friend in FriendModel.objects.filter(user_id1=user_id):
            friends.append(friend.user_id2)

        for friend in FriendModel.objects.filter(user_id2=user_id):
            friends.append(friend.user_id1)

        return friends

    def isFriend(self, user_id1, user_id2):

        return user_id2 in self.getFriends(user_id1)

    def deleteFriend(self, user_id1, user_id2):

        first = FriendModel.objects.filter(user_id1=user_id1, user_id2=user_id2)
        if (first.count() == 1):
            first.delete()
            return True

        second = FriendModel.objects.filter(user_id1=user_id2, user_id2=user_id1)
        if (second.count() == 1):
            second.delete()
            return True

        return False

