# AUTOGENERATED! DO NOT EDIT! File to edit: 06_download.ipynb (unless otherwise specified).

__all__ = ['DownloadVersion']

# Cell
import requests
import pathspec
import time
from pathlib import Path, PurePosixPath
from .lookup import Lookup
from .conf import CLI_ENDPOINT

# Cell
class DownloadVersion(Lookup):
    path = "."
    dest_path = "."
    project_id = ""
    version = ""
    api = CLI_ENDPOINT

    def __init__(self,
                 path=".",
                 project_id=None,
                 version=None,
                *args, **kwargs):
        api = None
        if "api" in kwargs:
            api = kwargs.pop("api")
        super().__init__(*args, **kwargs)
        if api != None:
            self.api = api
        assert project_id  != None
        if "v" in f"{version}":
            version = version.replace("v", "")
            try:
                version = int(version)
            except:
                raise Exception("Version must be a number or in the format v1, v2, v3, and so on.")
        self.path = Path(path).resolve()
        self.version = version
        self.project_id = project_id
        self.endpoint = f"{self.api}/projects/{project_id}/versions/{version}/download/"

    def save_from_url(self, dest, url, force=True):
        dest_path = Path(dest)
        if not force:
            if dest_path.exists():
                print(f"{dest_path} already exists")
                return None
        dest_path_parent = dest_path.resolve().parent
        dest_path_parent.mkdir(parents=True, exist_ok=True)
        # NOTE the stream=True parameter below
        with requests.get(url, stream=True) as r:
            r.raise_for_status()
            with open(dest_path, 'wb') as f:

                for chunk in r.iter_content(chunk_size=8192):
                    # If you have chunk encoded response uncomment if
                    # and set chunk_size parameter to None.
                    #if chunk:
                    f.write(chunk)
        return dest

    def download(self, overwrite=False):
        r = self.http_get(self.endpoint)
        self.handle_invalid_lookup(r, expected_status_code=200)
        files = r.json()

        for fdict in files:
            fname = fdict['fname']
            furl = fdict['url']
            dest = PurePosixPath(self.path / fname)
            print("Downloading", fname, "to", dest)
            self.save_from_url(dest, furl, force=overwrite)
        return