import pandas as pd
import os
from typing import List


def read_hr_file(path: str, game_id: int, player_id: int) -> List[int]:
    """Read an HR file and return a list with the HR values. If the file does not exist, return an empty list."""
    filename = path + "HR_G{:02d}_P{:02d}.csv".format(game_id, player_id)
    if os.path.isfile(filename):
        df = pd.read_csv(filename, sep=",")
        hr_data = df["HR"].values
        return hr_data
    else:
        return []


def read_playing_file(path: str, game_id: int, player_id: int) -> List[int]:
    """Read a PLAYING file and return a list with the playinf/non playing values.
    If the file does not exist, return an empty list."""
    filename = path + "PLAYING_G{:02d}_P{:02d}.csv".format(game_id, player_id)
    if os.path.isfile(filename):
        df = pd.read_csv(filename, sep=",")
        playing_data = df["PLAYING"].values
        return playing_data
    else:
        return []


def read_game_file(path: str, game_id: int,  field: str) -> List[int]:
    """Read a GAME file and returns a list with the game values. if the file does not exist, return an empty list."""
    filename = path + "GAME_{:02d}.csv".format(game_id)
    if os.path.isfile(filename):
        df = pd.read_csv(filename, sep=",")
        if field == "QUARTER":
            game_data = df["QUARTER"].values
        elif field == "ANALYSIS":
            game_data = df["ANALYSIS"].values
        elif field == "ATTACK_DEF":
            game_data = df["ATTACK_DEF"].values
        elif field == "OWN_POINTS":
            game_data = df["OWN_POINTS"].values
        elif field == "OPP_POINTS":
            game_data = df["OPP_POINTS"].values
        else:
            game_data = []
        return game_data
    else:
        return []


def save_matrix_to_excel(filename: str, matrix: List[List[float]], rows_name: List[str], columns_name: List[str]) -> None:
    """Save a matrix to an Excel file. 0 elements are saved as empty strings."""
    matrix = [[x if x != 0 else '' for x in row] for row in matrix]
    df = pd.DataFrame(matrix)
    df.index = rows_name
    df.columns = columns_name
    df.to_excel(filename, index=True, header=True)
