from __future__ import annotations

from django.db import models

from django.db.models import QuerySet

import time

# Create your models here.

class GameModel(models.Model):

    finished = models.BooleanField(default = False)
    started = models.BooleanField(default = False)
    winner_id = models.IntegerField(default = -1)
    start_timestamp = models.BigIntegerField(null = True, blank = True)
    stop_timestamp = models.BigIntegerField(null = True, blank = True)
    game_type = models.CharField(max_length = 60, default = "pong")
    
    def create(self, game_type: str, players_id: list[int]):
        self.game_type = game_type
        self.save()
        for player_id in players_id:
            GameMembersModel(game_id = self.pk, player_id = player_id).save()
        return self.pk

    def start(self):
        self.start_timestamp = round(time.time() * 1000, 1)
        self.started = True
        self.save()
    
    def finish(self, winner_id):
        self.winner_id = winner_id
        self.finished = True
        self.stop_timestamp = round(time.time() * 1000, 1)
        self.save()
    
    def get_players_id(self):
        return [game_player.player_id for game_player in GameMembersModel.objects.filter(game_id = self.pk)]
    
    def get_score_by_player_id(self, player_id: int) -> list[int]:
        query: QuerySet = GameGoalModel.objects.filter(game_id = self.pk, player_id = player_id)
        score_data: list[int] = [game_goal.timestamp for game_goal in query]
        
        return score_data
    
    def add_goal(self, goal_taker_id: int):
        
        timestamp: int = round(time.time() * 1000, 1) - self.start_timestamp
        
        goal_model: GameGoalModel = GameGoalModel.objects.create(player_id = goal_taker_id, game_id = self.pk, timestamp = timestamp)
        
        goal_model.save()
        
        return timestamp

class GameMembersModel(models.Model):
    game_id = models.IntegerField()
    player_id = models.IntegerField()
    
class GameGoalModel(models.Model):
    
    game_id = models.IntegerField()
    player_id = models.IntegerField()
    timestamp = models.IntegerField()