import csv


def extract_scan_params_csv(scan_params_csv):
    """
    Function to extract the site-based scan parameters from a csv file
    and return a dictionary of their values

    Parameters
    ----------
    scan_params_csv : string
        filepath to the scan parameters csv file

    Returns
    -------
    site_dict : dictionary
        a dictionary where site names are the keys and the scan
        parameters for that site are the values stored as a dictionary
    """

    # Import packages

    # Init variables
    csv_open = open(scan_params_csv, 'r')
    site_dict = {}

    # Init csv dictionary reader
    reader = csv.DictReader(csv_open)

    placeholders = ['None', 'NONE', 'none', 'All', 'ALL', 'all', '', ' ']

    keys = {"TR (seconds)": "TR",
            "TE (seconds)": "TE",
            "Reference (slice no)": "reference",
            "Acquisition (pattern)": "acquisition",
            "FirstTR (start volume index)": "first_TR",
            "LastTR (final volume index)": "last_TR"}

    # Iterate through the csv and pull in parameters
    for dict_row in reader:

        if dict_row['Site'] in placeholders:
            site = 'All'
        else:
            site = dict_row['Site']

        sub = "All"
        if "Participant" in dict_row.keys():
            if dict_row["Participant"] not in placeholders:
                sub = dict_row["Participant"]

        ses = 'All'
        if 'Session' in dict_row.keys():
            if dict_row['Session'] not in placeholders:
                ses = dict_row['Session']

        if ses != 'All':
            # for session-specific scan parameters
            if site not in site_dict.keys():
                site_dict[site] = {}
            if sub not in site_dict[site].keys():
                site_dict[site][sub] = {}

            site_dict[site][sub][ses] = {keys[key]: val
                                         for key, val in dict_row.items()
                                         if key != 'Site' and
                                         key != 'Participant' and
                                         key != 'Session' and key != 'Series'}

            # Assumes all other fields are formatted properly, but TR might
            # not be
            #site_dict[site][sub][ses]['tr'] = \
            #    site_dict[site][sub][ses].pop('tr (seconds)')

        elif sub != "All":
            # participant-specific scan parameters
            if site not in site_dict.keys():
                site_dict[site] = {}
            if sub not in site_dict[site].keys():
                site_dict[site][sub] = {}

            site_dict[site][sub][ses] = {keys[key]: val
                                         for key, val in dict_row.items()
                                         if key != 'Site' and
                                         key != 'Participant' and
                                         key != 'Session' and key != 'Series'}

            # Assumes all other fields are formatted properly, but TR might
            # not be
            #site_dict[site][sub][ses]['tr'] =
            #    site_dict[site][sub][ses].pop('tr (seconds)')

        else:
            # site-specific scan parameters only
            if site not in site_dict.keys():
                site_dict[site] = {}
            if sub not in site_dict[site].keys():
                site_dict[site][sub] = {}

            site_dict[site][sub][ses] = {keys[key]: val
                                         for key, val in dict_row.items()
                                         if key != 'Site' and
                                         key != 'Participant' and
                                         key != 'Session' and key != 'Series'}

            # Assumes all other fields are formatted properly, but TR might
            # not be
            #site_dict[site][sub][ses]['tr'] = \
            #    site_dict[site][sub][ses].pop('tr (seconds)')

    return site_dict