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

__all__ = ['find_backward', 'find_data', 'create_file_path', 'download_data']

# Cell
import glob
import warnings
import urllib
import os

# Cell
def find_backward(folder='input',path='./'):
    """
        Go backward in the hierarchy to find the specified folder from path
    """
    res=[p for p in glob.glob(path+'*') if folder in p]
    if not res==[] :
        return res[0]
    return find_backward(folder,path=path+'../')

# Cell

def find_data(name,folder='input'):
    # Foward to find the specified data
    files=glob.glob(f"{find_backward(folder)}/{name}")
    files=glob.glob(f"{find_backward(folder)}/**/{name}")
    if len(files)==1:
        return(files[0])
    elif len(files)>1:
        warnings.warn(f'Warining : many files corespond : {files}\nFile path return : {files[0]}')
        return(files[0])
    else :
        print('No data found')

# Cell

def create_file_path(file_name):
    """Ensure that the right file structure is created before creating a file"""
    if not '/' in file_name :
        return None
    directories=file_name.split('/')[:-1]
    not_created=[]
    while not os.path.isdir('/'.join(directories+[''])):
        not_created.append(directories.pop())
        if not directories :
            break
    for _ in range(len(not_created)):
        directories.append(not_created.pop())
        os.mkdir('/'.join(directories+['']))


# Cell

def download_data(url,file_name,folder='download_data'):
    """Download everything urlretrieve and put it at the right place"""

    dir_path=f"{find_backward(folder='input')}/{folder}/"
    file_path=dir_path+file_name

    if not os.path.isdir(dir_path):
        os.mkdir(dir_path)

    if os.path.isfile(file_path):
        warnings.warn(f'Data {file_name} already in folder {folder}')
        return None


    create_file_path(file_path)

    urllib.request.urlretrieve(url,file_path)