# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/utils/files.ipynb.

# %% auto 0
__all__ = ['upsert_folder', 'change_extension', 'download_zip']

# %% ../../nbs/utils/files.ipynb 2
import os
import pathlib
import zipfile
import io

# %% ../../nbs/utils/files.ipynb 3
def upsert_folder(folder_path: str, debug_prn: bool = False):
    folder_path = os.path.dirname(folder_path)

    if debug_prn:
        print(
            {
                "upsert_folder": os.path.abspath(folder_path),
                "is_exist": os.path.exists(folder_path),
            }
        )

    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

# %% ../../nbs/utils/files.ipynb 5
def change_extension(file_path, new_extension):
    path = pathlib.PurePath(file_path)

    new_extension = new_extension if new_extension[0] == "." else "." + new_extension

    new_file_path = path.with_suffix( new_extension)
    return str(new_file_path)

# %% ../../nbs/utils/files.ipynb 7
def download_zip(
    output_folder,
    zip_bytes_content: bytes = None, # bytes or bytearray
    zip_file_path: str = None, # location of zip file
    is_unpack_archive: bool = True
):
    """save bytes content to a zip file then convert html to markdown"""
    zip = None
    if zip_bytes_content:
        zip = zipfile.ZipFile(io.BytesIO(zip_bytes_content), "r")

    if zip_file_path:
        zip = zipfile.ZipFile(zip_file_path)

    if not zip:
        raise Exception(
            "unable to generate zip file pass zip_bytes_content or zip_file_path"
        )
    
    
    if not is_unpack_archive and zip_bytes_content:
        output_folder = change_extension(output_folder, ".zip")
        upsert_folder(output_folder)

        with open(output_folder, 'wb') as f:
            f.write(zip_bytes_content)

        return f"successfully downloaded to {output_folder}"
    
    elif not is_unpack_archive and os.path.exists(zip_file_path):
        return f"zip available at {zip_file_path}"
    
    output_folder = output_folder if output_folder.endswith("/") else output_folder +'/'
    
    upsert_folder(output_folder)

    zip.extractall(output_folder)
    
    zip.close()

    file_ls = os.listdir(output_folder)
    return file_ls
