from django.contrib.auth import logout
from django.utils import timezone

from users.models import Player, Log

actions = Log.Actions

class BloonsaUtil:

    def __init__(self):
        self.tracking = True

    @staticmethod
    def get_ip(request):
        x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
        if x_forwarded_for:
            ip = x_forwarded_for.split(",")[-1].strip()
        else:
            ip = request.META.get("REMOTE_ADDR")
        return ip

    # Create a Player object for a User
    def init_player(self, request):
        if not request.user.is_authenticated:
            return
        player = Player.objects.filter(user=request.user).first()
        if player:
            return player
        ip = self.get_ip(request=request)
        player = Player(user=request.user,
                        creationIP=ip,
                        latestIP=ip)
        player.save()
        return player

    # Update activity timestamp and IP
    def tag_player(self, request):
        if not self.tracking:
            return
        if not request.user.is_authenticated:
            return
        player = Player.objects.filter(user=request.user).first()
        if not player:
            player = self.init_player(request=request)
        if player.banned:
            # TODO message popup?
            logout(request)
            return

        player.latestActivity = timezone.now()
        player.latestIP = self.get_ip(request=request)
        player.save()

    def log(self, action, note=None, player=None, request=None):
        if not self.tracking:
            return
        if not player:
            if not request or not request.user.is_authenticated:
                return
            player = self.init_player(request=request)
        item = Log(player=player,
                   action=action,
                   note=note)
        item.save()

bloonsa_util = BloonsaUtil()