from server.Files import save_file
from datetime import datetime
import os

class GameStorage:
  save_folder_dict = {
    "standart": "01_Standart",
    "duel": "02_Duels",
    "constrictor": "04_Constrictor",
  }

  def __init__(self, snake:str, path:str):
    self.snake_type = snake
    self.folder = path
    self.winner_snake_names = None
    self.turns = {}

  def start_new_game(self, game_info:dict, game_board:dict, snake:dict):
    self.init_game_board = game_board
    self.game_info = game_info
    self.my_snake_id = snake['id']
    self.moves = []
    self.now_date = datetime.now()

  def add_moves(self, turn:int, game_board:dict, my_move:str):
    self.turns[turn] = {
      "move": my_move,
      "game_board": game_board
    }

  def add_end_state(self, game_board:dict, snake_history_state:list[dict], final_turns:int):
    self.final_turns = final_turns
    self.snake_history = snake_history_state
    self._set_winner_snake_name(game_board['snakes'])

  def _set_winner_snake_name(self, snakes:list[dict]):
    if self.my_snake_id in [ x["id"] for x in snakes]:
      self.winner_snake_names = "me"
    else:
      self.winner_snake_names = [ x["name"] for x in snakes]
      if len(self.winner_snake_names) == 0:
        self.winner_snake_names = None

  def _get_type_of_gameboard(self):
    if len(self.init_game_board["snakes"]) == 2:
      return {"name": "duel", "is_ladder": True if self.game_info["source"] == "ladder" else False}
    elif self.game_info["ruleset"]["name"] == "constrictor":
      return {"name": "constrictor", "is_ladder": True if self.game_info["source"] == "ladder" else False}

    return {"name": "standart", "is_ladder": True if self.game_info["source"] == "ladder" else False}

  def _get_correct_folder_for_save_file(self, file_name:str, game_type:str, leader_board:bool, winner:bool):
    storage_folder = self.folder
    if leader_board:
      storage_folder = os.path.join(storage_folder, "00_Leaderboards")

    storage_folder = os.path.join(storage_folder, self.save_folder_dict[game_type])
    storage_folder = os.path.join(storage_folder, self.now_date.strftime('%Y'), self.now_date.strftime('%m_%B'), self.now_date.strftime('%d'))

    if winner:
      storage_folder = os.path.join(storage_folder, "Winner")
    else:
      storage_folder = os.path.join(storage_folder, "Lost")

    print(file_name, game_type, leader_board, winner)
    return os.path.join(storage_folder, file_name)

  def save(self, file_name:str, callback=None, **kwargs):
    if self.winner_snake_names == "me" and self.final_turns <= 10:
      return None

    game_type = self._get_type_of_gameboard()
    save_file_path = self._get_correct_folder_for_save_file(file_name, game_type["name"], game_type["is_ladder"], True if self.winner_snake_names == "me" else False)

    save_file(save_file_path, {
      "winner": self.winner_snake_names,
      "game": {
        "id": self.game_info["id"],
        "final_turns": self.final_turns,
        "map": self.game_info["map"],
        "type": game_type,
        "ruleset": self.game_info["ruleset"],
      },
      "moves": self.turns,
      "snake": {
        "type": self.snake_type,
        "calculations": self.snake_history,
      },
    }, callback=callback, **kwargs)

  def __str__(self):
    return f"<{self.__class__.__name__}> Snake: {self.snake_type}, Folder: {self.folder}, Winner: {self.winner_snake_names}, Old Moves: {self.moves}"
