import io
import base64


def send_bytes(writer, filename, mime_type=None, **kwargs):
    """
    Convert data written to BytesIO into the format expected by the Download component.
    :param writer: a writer that can write to BytesIO
    :param filename: the name of the file
    :param mime_type: mime type of the file (optional, passed to Blob in the javascript layer)
    :return: dict of data frame content (base64 encoded) and meta data used by the Download component
    """
    data_io = io.BytesIO()
    # Some pandas writers try to close the IO, we do not want that.
    data_io_close = data_io.close
    data_io.close = lambda: None
    # Write data content to base64 string.
    writer(data_io, **kwargs)
    data_value = data_io.getvalue()
    data_io_close()
    content = base64.b64encode(data_value).decode()
    # Wrap in dict.
    return dict(content=content, filename=filename, mime_type=mime_type, base64=True)