# -*- coding: utf-8 -*-
"""
Data loading function. This is generated by modifying the scanpy's data loading utility function.

"""
from pathlib import Path
import os
import warnings

def download_demo_data(file, git_url=None):
    """
    Download files for the tutorial.
    The downloaded file is saved in the local directory.
    """
    if git_url is None:
        git_url = "https://raw.githubusercontent.com/morris-lab/CellOracle/master/docs/demo_data"
    download_data_if_data_not_exist(path=file,
                                    backup_url=os.path.join(git_url, file))


def download_data_if_data_not_exist(path, backup_url):
    """Check if file is present otherwise download."""

    path = Path(path)
    if not path.is_file():
        _download(url=backup_url, path=path)


def _download(path: Path, url: str):
    print(f"Data not found in the local folder. Loading data from github. Data will be saved at {path.parent}")

    os.makedirs(path.parent, exist_ok=True)

    try:
        import ipywidgets
        from tqdm.auto import tqdm
    except ImportError:
        from tqdm import tqdm

    from urllib.request import urlopen, Request
    from urllib.error import URLError

    blocksize = 1024 * 8
    blocknum = 0

    try:
        req = Request(url)

        try:
            open_url = urlopen(req)
        except URLError:
            warnings.warn('Failed to open the url with default certificates, trying with certifi.')

            from certifi import where
            from ssl import create_default_context
            open_url = urlopen(req, context=create_default_context(cafile=where()))


        with open_url as resp:
            total = resp.info().get("content-length", None)
            with tqdm(
                unit="B",
                unit_scale=True,
                miniters=1,
                unit_divisor=1024,
                total=total if total is None else int(total),
            ) as t, path.open("wb") as f:
                block = resp.read(blocksize)
                while block:
                    f.write(block)
                    blocknum += 1
                    t.update(len(block))
                    block = resp.read(blocksize)

    except (KeyboardInterrupt, Exception):
        # Make sure file doesn’t exist half-downloaded
        if path.is_file():
            path.unlink()
        raise
