from numpy import random 
import os 
from dicom_to_cnn.tools.cleaning_dicom.folders import *


def generate_dict(number_of_roi:int, name:str, serie_description:str, body_part:str, roi_name:dict, interpreted_type:dict=None) -> dict:
    """a function to generate a dict with informations to generate DICOM SEG or DICOM RTSTRUCT file
    ! no more than 16 characters for each informations ! 

    Args:
        number_of_roi ([int]): [Total number of ROI in dicom file ]
        mode ([str]): ['rtstruct' or 'dicomseg']

    Returns:
        [dict]: [return dict with informations about ROI in it ]
    """

    results = {}
    results["ContentCreatorName"] = "dicom_to_cnn"
    random_number = random.randint(0,1e3)
    
    results["ClinicalTrialSeriesID"] = name #name of json

    results["ClinicalTrialTimePointID"] = "1"

    results["SeriesDescription"] = serie_description
    
    results["SeriesNumber"] = str(random_number)
    results["InstanceNumber"] = str(number_of_roi)

    results["BodyPartExamined"] = body_part

    results["segmentAttributes"] = []
    subliste = []
    for i in range(number_of_roi):
        subdict = {}
        subdict["labelID"]= i+1
        subdict["SegmentDescription"] = roi_name[i+1]

        subdict["SegmentAlgorithmType"] = "SEMIAUTOMATIC"
        subdict["SegmentAlgorithmName"] =  "DeepOncology"
        if interpreted_type is not None : 
            subdict['RTROIInterpretedType'] = interpreted_type[i+1]
        
        #subdict["SegmentedPropertyCategoryCodeSequence"] 
        subsubdict = {}
        subsubdict["CodeValue"] = "49755003"
        subsubdict["CodingSchemeDesignator"] = "SCT"
        subsubdict["CodeMeaning"] = "Morphologically Altered Structure"
        subdict["SegmentedPropertyCategoryCodeSequence"] = subsubdict

        #subdict["SegmentedPropertyTypeCodeSequence"] = {}
        subsubdict = {}
        subsubdict["CodeValue"] = "108369006"
        subsubdict["CodingSchemeDesignator"] = "SCT"
        subsubdict["CodeMeaning"] = "Neoplasm"
        subdict["SegmentedPropertyTypeCodeSequence"] = subsubdict
        subliste.append(subdict)

    results["segmentAttributes"].append(subliste)

    results["ContentLabel"] =  "SEGMENTATION"
    results["ContentDescription"] = "Image segmentation"
    results["ClinicalTrialCoordinatingCenterName"] = "dicom_to_cnn"

    return results

def save_dict_as_json(results:dict, directory:str) -> str :
    """a function to save the dict generated by 'generate_dict' function above

    Args:
        results ([dict]): [Dictionnary generated by 'generate_dict' function ]
        directory ([str]): [Name of directory to save the dict as json file ]

    Returns:
        [str]: [return the path name of the json file]
    """
    filename = results["ClinicalTrialSeriesID"]
    write_json_file(directory, filename, results)
    return os.path.join(directory, filename+'.json')
