import piexif


def get_field_value(field_tag, exif_blob):
    """
    Gets the raw value from the api response for the given tag
    Args:
        field_tag (str): EXIF tag name
        exif_blob (dict): decoded api response 

    Returns:
        unicode or None: the raw value of the specified EXIF tag

    """
    relevant_field = filter(lambda blob: blob['tag'] == field_tag, exif_blob)
    if not relevant_field:
        return None
    return relevant_field[0]['raw']['_content']


def map_exif_data(exif_blob):
    """
    Maps common EXIF fields to their Flickr counterparts. Not all the EXIF data is used.
    
    Args:
        exif_blob (dict): decoded api response 

    Returns:
        dict: EXIF data ready to be encoded 

    """
    zeroth_ifd = {
        piexif.ImageIFD.Make: get_field_value('Make', exif_blob),
        piexif.ImageIFD.Model: get_field_value('Model', exif_blob),
        piexif.ImageIFD.XResolution: (int(get_field_value('XResolution', exif_blob)), 1),
        piexif.ImageIFD.YResolution: (int(get_field_value('YResolution', exif_blob)), 1),
        piexif.ImageIFD.Software: get_field_value('Software', exif_blob),
        piexif.ImageIFD.DateTime: get_field_value('ModifyDate', exif_blob),
    }
    exif_ifd = {
        piexif.ExifIFD.DateTimeOriginal: get_field_value('DateTimeOriginal', exif_blob),
        piexif.ExifIFD.DateTimeDigitized: get_field_value('CreateDate', exif_blob),
    }
    first_ifd = {
        piexif.ImageIFD.Make: get_field_value('Make', exif_blob),
        piexif.ImageIFD.Software: get_field_value('Software', exif_blob),
    }

    exif_dict = {
        '0th': zeroth_ifd,
        'Exif': exif_ifd,
        '1st': first_ifd,
    }
    return exif_dict
