# 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, parent, P, stem
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=None):
    if save_html_to is None:
        save_html_to = parent(P(this_file_path)).resolve() / f'backups/{stem(this_file_path)}'
    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"
    Info(f"Backing up this version of notebook to {save_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)
    makedir(save_html_to)
    writelines([body], save_to)
    Info(f"Success!")
