import IPython

def create_new_cell(contents):
    # https://stackoverflow.com/questions/54987129/
    # how-to-programmatically-create-several-new-cells-in-a-jupyter-notebook

    from IPython.core.getipython import get_ipython

    shell = get_ipython()

    payload = dict(
        source="set_next_input",
        text=contents,
        replace=False,
    )
    shell.payload_manager.write_payload(payload, single=False)

for j in range(3):
    r = create_new_cell(f"print('hello {j}')")

shell = IPython.core.getipython.get_ipython()

shell.starting_dir

# %notebook "new.ipynb"

"""
Explanation: Creating templates
Programmatically creating new cells - first take
Trying to use IPython functionallity to make new cells
End of explanation
"""


in_nb = "/users/jepe/scripting/cellpy/dev_utils/papermill/pm_input_test.ipynb"
out_nb = "/users/jepe/scripting/cellpy/dev_utils/papermill/pm_output_test.ipynb"

import papermill as pm
from pathlib import Path

def create_template(template_name, autorun=False):
    datestamp = "20190810"
    name = "test"
    out_dir = "/users/jepe/scripting/cellpy/dev_utils/papermill"
    in_nb = input_notebook(template_name)
    out_nb = output_notebook(
        template_name, out_dir=out_dir, datestamp=datestamp, name=name
    )
    print(in_nb)
    print(out_nb)
    nb_node = pm.execute_notebook(
        str(in_nb.resolve()),
        str(out_nb.resolve()),
        prepare_only=not autorun,
        parameters=dict(a=3, b="anna"),
    )

    return nb_node

def output_notebook(template, out_dir=None, datestamp="20190810", name="test"):
    if out_dir is None:
        out_dir = Path()
    fname = f"{datestamp}_{name}_{template}.ipynb"
    path = Path(out_dir) / fname
    return path

def input_notebook(template="pm_input_test"):
    in_dir = "/users/jepe/scripting/cellpy/dev_utils/papermill"
    fname = f"{template}.ipynb"
    path = Path(in_dir) / fname
    return path

nb_node = create_template("pm_input_test", autorun=False)

"""
Explanation: Result:
Works only within jupyter, not jupyterlab. However, it could be used for loading just a single cell.
Testing PaperMill
End of explanation
"""


