from datetime import datetime
import requests
import zipfile
import io


def get_shares_file(date):
    """
    Download the file with the number of shares and returns bytes
    Args:
        date: Timestamp
    Returns: bytes
    """
    file_date = datetime.strftime(date, "%y%m%d")
    file_url = f'http://www.b3.com.br/pesquisapregao/download?filelist=IN{file_date}.zip'
    response = requests.get(file_url)

    # original zipfile. Inside this one, there is another zipfile
    zip_file = zipfile.ZipFile(io.BytesIO(response.content))

    # The zipfile that is inside the original zipfile. Inside this one, is the XML file
    zip_file2 = zipfile.ZipFile(io.BytesIO(zip_file.read(zip_file.namelist()[0])))

    # Inside the zip_file2 there are 2 xml files. We need the latest one.
    xml_bytes_data = zip_file2.read(max(zip_file2.namelist()))

    return xml_bytes_data