from pathlib import Path
import tempfile
import requests
import shutil
import io
import patoolib


def download_extract_zipped_file(url, file_ext):
    """
    Download a zipped folder to a temporary location, extract it to a temporary directory

    Parameters
    ----------
    url: str
        Url for where to download the file from
    file_ext:
        File extension

    Returns
    ----------
    pathlib.Path:
        Path to where the extracted files are saved
    """

    file_ext = file_ext.lower() if file_ext[0] == "." else "." + file_ext.lower()

    temp_file = Path(tempfile.NamedTemporaryFile(suffix=file_ext).name)
    temp_dir = Path(tempfile.TemporaryDirectory().name)

    with requests.get(url) as response:
        with open(temp_file, "wb") as out_file:
            shutil.copyfileobj(io.BytesIO(response.content), out_file)

    patoolib.extract_archive(str(temp_file), outdir=temp_dir, verbosity=0)

    temp_file.unlink()
    return temp_dir