# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/01_data.external.ipynb.

# %% auto 0
__all__ = ['pytennis_cfg', 'pytennis_path', 'URLs', 'untar_data']

# %% ../../nbs/01_data.external.ipynb 4
from fastcore.all import *
from fastdownload import FastDownload
from functools import lru_cache

# %% ../../nbs/01_data.external.ipynb 7
@lru_cache(maxsize=None)
def pytennis_cfg() -> Config: # Config that contains default download paths for `data`, `model`, `storage` and `archive`
    "`Config` object for fastai's `config.ini`"
    return Config(Path(os.getenv('PYTENNIS_HOME', '~/.pytennis')), 'config.ini', create=dict(
        data = 'data', archive = 'archive', storage = 'tmp', model = 'models'))

# %% ../../nbs/01_data.external.ipynb 10
def pytennis_path(folder:str) -> Path: 
    "Local path to `folder` in `Config`"
    return pytennis_cfg().path(folder)

# %% ../../nbs/01_data.external.ipynb 13
class URLs():
    "Global constants for dataset and model URLs."
    LOCAL_PATH = Path.cwd()
    S3  = 'https://pytennis-{VAR}.s3.eu-central-1.amazonaws.com/'
    URL =  S3.format(VAR='sample')

    S3_DATA    =  S3.format(VAR='data')
    S3_MODELS  =  S3.format(VAR='models')

    # main datasets
    ATP_2019_AUSTRALIAN_OPEN_SINGLES_FINAL = f'{S3_DATA}ATP_2019_AustralianOpen_Singles_Final.zip'
    ATP_2019_QUEENS_DOUBLES_FINAL = f'{S3_DATA}ATP_2019_Queens_Doubles_Final.zip'

    # Models


    def path(
        url:str='.', # File to download
        c_key:str='archive' # Key in `Config` where to save URL
    ) -> Path:
        "Local path where to download based on `c_key`"
        fname = url.split('/')[-1]
        local_path = URLs.LOCAL_PATH/('models' if c_key=='model' else 'data')/fname
        if local_path.exists(): return local_path
        return pytennis_path(c_key)/fname

# %% ../../nbs/01_data.external.ipynb 18
def untar_data(
    url:str, # File to download
    archive:Path=None, # Optional override for `Config`'s `archive` key
    data:Path=None, # Optional override for `Config`'s `data` key
    c_key:str='data', # Key in `Config` where to extract file
    force_download:bool=False, # Setting to `True` will overwrite any existing copy of data
    base:str='~/.pytennis' # Directory containing config file and base of relative paths
) -> Path: # Path to extracted file(s)
    "Download `url` using `FastDownload.get`"
    d = FastDownload(pytennis_cfg(), module=None, archive=archive, data=data, base=base)
    return d.get(url, force=force_download, extract_key=c_key)
