import logging


def get_subarray_info(params, subarray_table):
    """Find aperture-specific information from the subarray information config file

    Parameters:
    -----------
    params : dict
        Nested dictionary containing Mirage parameters.

    subarray_table : astropy.table.Table
        Table containing subarray definition information. Output from
        read_subarray_definition_file

    Returns:
    --------
    params : dict
        Updated nested dictionary
    """
    logger = logging.getLogger('mirage.utils.utils.get_subarray_info')

    array_name = params['Readout']['array_name']
    # For MASKSWB and MASKLWB apertures, the filter name is part of the aperture
    # name. But the subarray definition file contains only an entry for the aperture
    # name without the filter name. In that case, strip off the filter name here
    # before checking the definition file
    if '_MASKLWB' in array_name or '_MASKSWB' in array_name:
        pieces = array_name.split('_')
        array_name = '{}_{}'.format(pieces[0], pieces[1])

    if array_name in subarray_table['AperName']:
        mtch = array_name == subarray_table['AperName']
        namps = subarray_table['num_amps'].data[mtch][0]
        if namps != 0:
            params['Readout']['namp'] = int(namps)
        else:
            try:
                if ((params['Readout']['namp'] == 1) or
                   (params['Readout']['namp'] == 4)):
                    logger.info(("CAUTION: Aperture {} can be used with either "
                                 "a 1-amp or a 4-amp readout. The difference is a factor of 4 in "
                                 "readout time. You have requested {} amps.".format(subarray_table['AperName'].data[mtch][0],
                                                                                    params['Readout']['namp'])))
                else:
                    raise ValueError(("WARNING: {} requires the number of amps to be 1 or 4. Please set "
                                      "'Readout':'namp' in the input yaml file to one of these values."
                                      .format(array_name)))
            except KeyError:
                raise KeyError(("WARNING: 'Readout':'namp' not present in input yaml file. "
                                "{} aperture requires the number of amps to be 1 or 4. Please set "
                                "'Readout':'namp' in the input yaml file to one of these values."
                                .format(array_name)))
    else:
        raise ValueError(("WARNING: subarray name {} not found in the "
                          "subarray dictionary {}."
                          .format(array_name,
                                  params['Reffiles']['subarray_defs'])))
    return params