import json
import logging


def parse_json(json_file):
    """
    Parse json file.

    Parameters
    ----------
    json_file: json
        JSON file containing information about which subjects/sessions/scans to
        download from which project and where to store the files.

    JSON Keys
    ---------
    destination: string
        Directory to construct the BIDS structure
    project: string
        project ID on xnat that you wish to download from
    zero_pad: int 
        (DEPRECIATED), use num_digits instead
    num_digits: int
        Explicitly set how many digits you want your subject label to have
        (only useful for entirely numbered subject labels)
    subjects: list
        A list of subjects you wish to download scans from
    scan_dict: dictionary
        a dictionary/hash table where the keys are the scan names on xnat
        and the values are the reproin style scan names
    sub_dict: dictionary
        a dictionary/hash table where the keys are the subject labels on xnat
        and the values are the modified subject labels that you want to be
        displayed
    server: string
        The base URL to the xnat server (e.g. "https://central.xnat.org")
    session_labels: list
        (optional) (non-BIDS) If you want to replace the names of the sessions
        on xnat with your own list of scans.
    scan_labels: list
        (optional) a list of the scans you want to download (if you don't want to
        download all the scans).
    Returns
    -------
    input_dict:
        A dictionary containing the parameters specified in the JSON file
    """
    with open(json_file) as json_input:
        input_dict = json.load(json_input)
        # print(str(input_dict))
    mandatory_keys = ['destination', 'project', 'server']
    optional_keys = ['zero_pad', 'session_labels', 'subjects', 'scan_labels',
                     'scan_dict', 'num_digits', 'sub_dict', 'sub_label_prefix']
    total_keys = mandatory_keys+optional_keys
    # print("total_keys: "+str(total_keys))
    # are there any inputs in the json_file that are not supported?
    extra_inputs = list(set(input_dict.keys()) - set(total_keys))
    if extra_inputs:
        logging.warning('JSON spec key(s) not supported: %s' % str(extra_inputs))

    # are there missing mandatory inputs?
    missing_inputs = list(set(mandatory_keys) - set(input_dict.keys()))
    if missing_inputs:
        raise KeyError('option(s) need to be specified in input file: '
                       '%s' % str(missing_inputs))

    return input_dict