# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/globals.ipynb (unless otherwise specified).

__all__ = ['AddStringsMixin', 'LinkAllMixin', 'HANDLER', 'logger', 'USER_DIR', 'APP_DIR', 'DEFINITIONS', 'CONFIG',
           'py_warnings_logger', 'getFilesFromDEFINITIONS', 'loadCSS', 'loadJS', 'loadJS', 'get_nb_url']

# Comes from custom_widgets.ratio.ipynb, cell
import numpy as np

class AddStringsMixin():
    ''' Like numpy.char.add but it works on dtype np.object'''

    def add_strings(self, first, second):
        if isinstance(first,str):
            first = [first] * len(second)
        if isinstance(second,str):
            second = [second] * len(first)
        if len(first) != len(second):
            raise ValueError('If adding arrays, they must have matching lengths')
        return np.array([first[i] + second[i] for i in range(len(first))], dtype=np.object)

# Comes from custom_widgets.ratio.ipynb, cell
import traitlets
class LinkAllMixin():

    def link_all(self, source, destination):
        dest_traits = destination.traits()
        for trait in source.traits():
            if trait in dest_traits:
                traitlets.link((source, trait), (destination, trait))

# Cell
import os, time, pathlib, urllib, configparser
from notebook import notebookapp
import traitlets
from IPython.display import HTML
import logging
import warnings

# Cell
from .log import LogHandlerWidget

HANDLER = LogHandlerWidget()
logger = HANDLER.getLogger(__name__)

# Cell
USER_DIR = os.path.join(os.path.expanduser("~"),'.superpower_gui')
if not os.path.exists(USER_DIR):
    os.makedirs(USER_DIR)

APP_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

# Cell
if not 'definitions.ini' in os.listdir(APP_DIR):
    raise Exception("Required file 'definitions.ini' not found in %s" % APP_DIR)
DEFINITIONS = configparser.ConfigParser()
DEFINITIONS.read(os.path.join(APP_DIR, 'definitions.ini'))

# Cell
for filetype in ('CSS', 'JS'):
    if filetype in DEFINITIONS:
        for file in DEFINITIONS[filetype]:
            DEFINITIONS[filetype][file] = os.path.join(APP_DIR, DEFINITIONS[filetype][file].strip('\"').strip('\''))

# Cell
CONFIG = configparser.ConfigParser()
CONFIG.read(os.path.join(USER_DIR, 'config.ini'))

# Cell
try:
    if 'LOG' in CONFIG and 'logging_level' in CONFIG['LOG']:
        HANDLER.level = getattr(logging, CONFIG['LOG']['logging_level'])
except:
    HANDLER.level = getattr(logging, DEFINITIONS['LOG']['logging_level'])

# Cell
logging.captureWarnings(True)
py_warnings_logger = logging.getLogger('py.warnings')
py_warnings_logger.addHandler(HANDLER)

# Cell
def getFilesFromDEFINITIONS(filetype, extension):
    files = []
    for filedir in DEFINITIONS[filetype]:
        files += [os.path.join(DEFINITIONS[filetype][filedir] ,f ) for f in os.listdir(DEFINITIONS[filetype][filedir]) if f.endswith('.css')]
    return files

def loadCSS():
    logger.info('Loading css files...')
    files = getFilesFromDEFINITIONS('CSS', '.css')
    for file in files:
        with open(file, 'r') as f:
            try:
                filestr = '<style>\n' + f.read() + '\n</style>'
                display(HTML(filestr))
                logger.info('\t%s' % file)
            except:
                logger.exception('Error loading css file %s' % file)

def loadJS():
    files = getFilesFromDEFINITIONS('JS', '.js')
    logger.info('Loading js files...')
    for file in files:
        display(Javascript(file))
        logger.info('\t%s' % file)

loadCSS()
loadJS()

# Cell
def loadJS(self, files):
    for file in files:
        display(Javascript(file))
        logger.info(file + ' loaded')

# Cell
def get_nb_url(hostname='localhost', port=8888): #hostname='mygeohub.org'
    nb_servers = list(notebookapp.list_running_servers())
    if len(nb_servers) == 0:
        raise Exception('This application should be run from a Jupyter notebook.')

    url = None
    if hostname == 'localhost':
        for server in nb_servers:
            if server['hostname'] == hostname and server['port'] == port:
                url = server['url']
                nb_server  = server
        if not url:
            raise Exception('Jupyter notebooks server not found at localhost port %s' % str(port))
    else:
        try: # to get session url of jupyter-notebook tool on mygeohub.com
            session = os.environ['SESSION']
            for server in nb_servers:
                if session in server['base_url']:
                    nb_server = server
                    url = urllib.parse.urlunparse(('https', hostname, server['base_url'], None, None, None))
        except KeyError:
            raise Exception('Remote session not found on %s' % hostname)

    return urllib.parse.urljoin(url, server['base_url'])

#NB_URL = get_nb_url(hostname='localhost', port=8888)