# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_mknb.ipynb.

# %% auto 0
__all__ = ['new_nb']

# %% ../nbs/00_mknb.ipynb 3
import re
from string import Template

from nbdev.config import get_config
from nbdev.sync import write_nb, mk_cell
from nbdev.doclinks import nbglob

from fastcore.xtras import Path

from fastcore.foundation import AttrDict, L
from fastcore.script import call_parse

# %% ../nbs/00_mknb.ipynb 4
_default_exp = Template("#| default_exp $export")
_title = Template("# $title\n")
_description = Template("> $description")
_export = "#| hide\nimport nbdev; nbdev.nbdev_export()"

# %% ../nbs/00_mknb.ipynb 5
def _mk_nb(title,desc,exp=None):
    nb = AttrDict(
        cells=L(),
        metadata={},
        nbformat=4,
        nbformat_minor=5
    )
    if exp is not None: 
        nb.cells.append(mk_cell(exp))
    nb.cells.append(mk_cell(title+desc, "markdown"))
    nb.cells.append(mk_cell(""))
    if exp is not None:
        nb.cells.append(mk_cell(_export))
    nb.cells = list(nb.cells)
    # return dict(nb)
    return nb

# %% ../nbs/00_mknb.ipynb 6
@call_parse
def new_nb(
    name:str, # The name of the newly created notebook
    module:str = None, # The name of the exported module it will generate
    title:str = None, # The title header in the notebook
    description:str = None, # The description that will go under the title header
    nprefix:int = None, # if > 0, will be the first number in the filename
    nsuffix:int = None, # If > 0, will be the second number in the filename
):
    "Creates a new base nbdev notebook named {nprefix}{nsuffix}_{name}.ipynb"
    cfg = get_config()
    nbs = nbglob(
        cfg.nbs_path,
        file_glob="*.ipynb",
        file_re="^[0-9]",
        skip_folder_re="^[_.]"
    )
    nbs = nbs.map(
        lambda x: Path(x).name.replace(".ipynb","")
    )
    nbs.sort()
    title = _title.substitute(title=title or "No Title")
    descrip = _description.substitute(description=description or "Fill me in!")
    if module is not None:
        module = _default_exp.substitute(export=module)
    if len(nbs) > 0:
        nums = nbs.map(
            lambda x: list(re.search("^[0-9][0-9]?", x).group(0))
        ).map(lambda x: list(map(int, x)))
        if nprefix is None:
            nprefix = max(o[0] for o in nums)
        if nsuffix is None:
            nsuffix = max(o[1] for o in nums)
    else:
        nprefix, nsuffix = 0,0
    nsuffix += 1
    nbpath = cfg.nbs_path/f'{nprefix}{nsuffix}_{name}.ipynb'
    write_nb(_mk_nb(title, descrip, module), nbpath)
