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

# %% auto 0
__all__ = ['is_in_notebook', 'save_notebook', 'backup_this_notebook']

# %% ../nbs/jupyter_notebook.ipynb 2
import importlib
import os, sys, json, time, hashlib
from IPython.display import display, Javascript
import nbformat
from nbconvert import HTMLExporter
from .paths import stems, Glob
from .markup import read_json, writelines, makedir
from .logger import Info

# %% ../nbs/jupyter_notebook.ipynb 3
def is_in_notebook():
    try:
        # Test adapted from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py
        get_ipython = sys.modules["IPython"].get_ipython
        if "IPKernelApp" not in get_ipython().config:
            raise ImportError("console")

        return importlib.util.find_spec("IPython") is not None
    except (AttributeError, ImportError, KeyError):
        return False

# %% ../nbs/jupyter_notebook.ipynb 4
def save_notebook(file_path):
    start_md5 = hashlib.md5(open(file_path, "rb").read()).hexdigest()
    display(Javascript("IPython.notebook.save_checkpoint();"))
    current_md5 = start_md5

    while start_md5 == current_md5:
        time.sleep(1)
        current_md5 = hashlib.md5(open(file_path, "rb").read()).hexdigest()
    Info(f"Saved the notebook at {file_path}!")


def backup_this_notebook(this_file_path, save_html_to):
    assert save_html_to
    save_notebook(this_file_path)

    this_notebook = nbformat.reads(
        json.dumps(read_json(this_file_path)),
        as_version=4,
    )

    html_exporter = HTMLExporter(template_name="classic")
    (body, resources) = html_exporter.from_notebook_node(this_notebook)
    available_number = max([int(i) for i in stems(Glob(save_html_to))], default=-1) + 1
    save_to =  f"{save_html_to}/{available_number:04}.html"
    makedir(save_html_to)
    writelines([body], save_to)
    Info(f"Backed a new version of notebook at {save_to}")
