from server.GameBoard import GameBoard
from server.Files import save_file

import json, os

class LocalStorage:
  def __init__(self, file_path:str, **kwargs):
    self.save_folder_dict = {
      "standard": "01_Standard",
      "duel": "02_Duels",
      "constrictor": "04_Constrictor",
      "solo": "05_Solo",
    }
    self.file_path = file_path

  def _get_correct_folder_for_save_file(self, game_board:GameBoard, file_name:str, game_type:str, leader_board:bool, winner:bool):
    storage_folder = self.file_path
    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, game_board.now_date.strftime('%Y'), game_board.now_date.strftime('%m_%B'), game_board.now_date.strftime('%d'))

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

    return os.path.join(storage_folder, file_name)

  async def save(self, game_board:GameBoard):
    game_type = game_board.get_type_of_game()
    save_file_path = self._get_correct_folder_for_save_file(
      game_board,
      f"{game_board.snake_class.__class__.__name__}_{game_board.now_date.strftime('%H-%M-%S')}_{game_board.id}.json",
      game_type["name"],
      game_type["is_ladder"],
      True if game_board.winner_snake_names and "me" in game_board.winner_snake_names else False
    )

    await save_file(save_file_path, {
      "winner": game_board.winner_snake_names,
      "game": {
        "url": game_board.url,
        "id": game_board.id,
        "final_turns": game_board.turn,
        "map": game_board.map,
        "type": game_type,
        "ruleset": game_board.ruleset,
      },
      "moves": game_board.turns,
      "snake": {
        "type": game_board.snake_class.__class__.__name__,
        "calculations": game_board.snake_class.get_history(),
      },
    }, callback=json.dump, indent=2, ensure_ascii=False)

  def cleanup(self):
    pass
