from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Player(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True, related_name="player")
    # Logging
    creationIP = models.GenericIPAddressField()
    latestIP = models.GenericIPAddressField()
    creationDate = models.DateTimeField(default=timezone.now)
    latestActivity = models.DateTimeField(default=timezone.now)
    suspectedCheater = models.BooleanField(default=False)  # This should be set when tripping the anti-cheat
    # States
    suspended = models.BooleanField(default=False)  # This is a shadow-ban, stats will still save but not all will show up on leaderboards
    banned = models.BooleanField(default=False)  # Account gets logged out upon logging in
    admin = models.BooleanField(default=False)  # Ability to suspend/ban other players


    # If bloonsa_levels_played gets replaced then this needs to be updated
    @property
    def bloonsa_levels_played_count(self):
        return self.bloonsa_levels_played.count()

    @property
    def bloonsa_levels_beaten_count(self):
        return self.bloonsa_level_scores.filter(clear=True).count()

    def has_beaten_bloonsa_level(self, level):
        bool(self.bloonsa_level_scores.filter(clear=True, level=level).first())

    def __str__(self):
        statesDict = {
            "cheater": "😈" if self.suspectedCheater else "",
            "suspended": "🔒" if self.suspended else "",
            "banned": "❌" if self.banned else "",
            "admin": "👑" if self.admin else "",
        }
        states = "".join(statesDict.values()) + " "
        return f"{states}{self.user} - {self.latestIP}".strip(" ")


class Log(models.Model):
    class Actions(models.IntegerChoices):
        login = 0, "Logged in"
        register = 1, "Registered"
        logout = 2, "Logged out"
        bloonsa_load_level_by_id = 100, "Loaded a level via ingame ID box"
        bloonsa_load_level_by_url = 101, "Loaded a level via URL"
        bloonsa_load_random_level = 102, "Loaded a random level"
        bloonsa_submit_score = 103, "Submitted a score on level_id"
        bloonsa_rate_level = 104, "Rated a level"

    player = models.ForeignKey(Player, related_name="log", on_delete=models.CASCADE, null=True)
    action = models.IntegerField(choices=Actions)
    timestamp = models.DateTimeField(default=timezone.now)
    note = models.TextField(null=True)

    def __str__(self):
        return f"{self.player.user.username} - {self.get_action_display()} <{self.note or ''}>"