'''
  This script initializes Jupyter's configuration such as passwords and other
  things. It is run by IPython hence why it can use functions like get_config().
'''
import os
import pathlib
import sys
from jupyter_server.auth import passwd
import jupyterlab

c = get_config()

c.ServerApp.password = passwd("{{ password }}")

jupyterlab_dir = pathlib.Path(os.environ['JUPYTERLAB_DIR'])

# symlink all schemas in a folder, jupyter seems to assume that everything is installed
# in the same place.
schemas_dir = jupyterlab_dir / 'schemas'
if not schemas_dir.exists():
  schemas_dir.mkdir()
for p in sys.path:
  for schema in (pathlib.Path(p) / 'share' / 'jupyter' / 'lab' / 'schemas').glob('*/'):
    dest = (schemas_dir / schema.name)
    if dest.exists():
      dest.unlink()
    dest.symlink_to(schema)
c.LabServerApp.schemas_dir = str(schemas_dir)

# static really needs to be a sub-folder of $JUPYTERLAB_DIR
static = pathlib.Path(jupyterlab.__file__).parent.parent / 'share' / 'jupyter' / 'lab' / 'static'
static_dir = jupyterlab_dir  / 'static'
if static_dir.exists():
  static_dir.unlink()
static_dir.symlink_to(static)

c.LabServerApp.themes_dir = str(pathlib.Path(jupyterlab.__file__).parent / 'themes')

c.ServerApp.jpserver_extensions = {
  'notebook': True,
  'jupyter_lsp':True,
  'jupyter_server_terminals': True,
  'jupyterlab': True,
  'notebook_shim': True,
}

try:
  os.environ['PATH'] = "{{ gcc_location }}/bin" + os.pathsep + os.environ['PATH']
except KeyError:
  os.environ['PATH'] = "{{ gcc_location }}/bin"

try:
  os.environ['PYTHONPATH'] = "{{ cythonplus_repository }}" + os.pathsep + os.environ['PYTHONPATH']
except KeyError:
  os.environ['PYTHONPATH'] = "{{ cythonplus_repository }}"
