import json


def match_epi_fmaps(bold_pedir, epi_fmap_one, epi_fmap_params_one,
                    epi_fmap_two=None, epi_fmap_params_two=None):
    """Parse the field map files in the data configuration and determine which
    ones have the same and opposite phase-encoding directions as the BOLD scan
    in the current pipeline.

    Example - parse the files under the 'fmap' level, i.e. 'epi_AP':
        anat: /path/to/T1w.nii.gz
        fmap:
          epi_AP:
            scan: /path/to/field-map.nii.gz
            scan_parameters: <config dictionary containing phase-encoding
                              direction>
        func:
          rest_1:
            scan: /path/to/bold.nii.gz
            scan_parameters: <config dictionary of BOLD scan parameters>

    1. Check PhaseEncodingDirection field in the metadata for the BOLD.
    2. Check whether there are one or two EPI's in the field map data.
    3. Grab the one or two EPI field maps.
    """

    fmap_dct = {epi_fmap_one: epi_fmap_params_one}
    if epi_fmap_two and epi_fmap_params_two:
        fmap_dct[epi_fmap_two] = epi_fmap_params_two

    opposite_pe_epi = None
    same_pe_epi = None

    for epi_scan in fmap_dct.keys():
        scan_params = fmap_dct[epi_scan]
        if not isinstance(scan_params, dict) and ".json" in scan_params:
            with open(scan_params, 'r') as f:
                scan_params = json.load(f)
        if "PhaseEncodingDirection" in scan_params:
            epi_pedir = scan_params["PhaseEncodingDirection"]
            if epi_pedir == bold_pedir:
                same_pe_epi = epi_scan
            elif epi_pedir[0] == bold_pedir[0]:
                opposite_pe_epi = epi_scan

    return (opposite_pe_epi, same_pe_epi)