import six
import base64


def to_base64(dataframe_plot, img_fmt=None):
    """Convert a plot into base64-encoded graph (PNG by default)

    Arguments:
        ataframe_plot (AxesSubplot):
            Figure obtained from drawing a dataframe object

        img_fmt (Optional[str]):
            Format of the resulting image. This format is tightly coupled to
            the backend used by matplotlib. Defaults to 'png'.
    Return:
        str
    """
    if not img_fmt:
        img_fmt = 'png'

    try:  # check there's data and the backend supports the output format
        assert (dataframe_plot.has_data() and img_fmt in
                dataframe_plot.get_figure().canvas.get_supported_filetypes())
    except AssertionError:
        return ''

    fbuffer = six.BytesIO()
    fig = dataframe_plot.get_figure()
    fig.savefig(fbuffer,
                format=img_fmt,
                bbox_inches='tight')
    fbuffer.seek(0)
    encoded_plot = six.b('data:image/{0};base64,'
                         .format(img_fmt)) + base64.b64encode(fbuffer.read())
    fbuffer.close()
    return encoded_plot