from dicom_to_cnn.model.petctviewer.CsvReader import CsvReader
import numpy as np 

"""functions to get informations about ROI volume in CSV file generated by petctviewer.org
"""
def get_total_volume(csv_path:str) -> float:
    """get total volume of all ROI in CSV file

    Args:
        csv_path (str): [path of the CSV file]

    Returns:
        [float]: [total volume of tumor]
    """
    csv_objet = CsvReader(csv_path)
    total_volume = float(csv_objet.get_sum_row()[3])
    return total_volume


def keep_csv_higher_volume(liste_csv_path:list) -> list:
    """function to

    Args:
        liste_csv_path ([list]): [list of CSV file path]

    Returns:
        ([list]) : [return the CSV file path with the higher volume]
    """
    volume = []
    for csv_file in liste_csv_path : 
        volume.append(get_total_volume(csv_file))
    index_maxi = volume.index(np.max(volume))
    if type(index_maxi) == list: 
        index_maxi = index_maxi[0]
    index = np.arange(len(volume)).tolist()
    remove = []
    for i in index:
        if i != index_maxi : 
            remove.append(liste_csv_path[i])
    for r in remove : 
        liste_csv_path.remove(r)
    return liste_csv_path


def get_sum_rois_volume(list_results_row:list) -> float:
    """sum all ROIs volume

    Args:
        liste ([list]): [List of every ROI results row from CSV file]

    Returns:
        [float]: [Return the sum of ROIs volume]
    """
    volume = float(0)
    for i in range(len(list_results_row)):
        volume += float(list_results_row[i][3])

    return volume


def get_difference_volume(csv_path:str) -> tuple :
    """Calcul the difference between volume and sum of every ROI volume

    Args:
        csv_path ([str]): [CSV file path]

    Returns:
        [tuple]: [Return total_volume, sum of every ROIs volume, and difference between the 2]
    """
    csv_objet = CsvReader(csv_path)
    total_volume = float(csv_objet.get_sum_row()[3])

    liste = csv_objet.get_rois_results()

    sum_volume = get_sum_rois_volume(liste)
    return total_volume, sum_volume, abs(sum_volume - total_volume)


