#-----------------------------------------------------------------------------
#  Copyright (C) 2013 The IPython Development Team
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------

import os

from concurrent.futures import ThreadPoolExecutor

from tornado import web, httpserver, ioloop, log
from tornado.httpclient import AsyncHTTPClient

import tornado.options
from tornado.options import define, options

from jinja2 import Environment, FileSystemLoader

from IPython.config import Config
from IPython.nbconvert.exporters import HTMLExporter
from IPython.nbconvert.filters import markdown2html

from .handlers import handlers, CustomErrorHandler
from .cache import DummyAsyncCache, AsyncMemcache
from .github import AsyncGitHubClient

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------

here = os.path.dirname(__file__)
pjoin = os.path.join

def nrhead():
    try:
        import newrelic.agent
    except ImportError:
        return ''
    return newrelic.agent.get_browser_timing_header()

def nrfoot():
    try:
        import newrelic.agent
    except ImportError:
        return ''
    return newrelic.agent.get_browser_timing_footer()

def main():
    """docstring for main"""
    define("port", default=5000, help="run on the given port", type=int)
    define("cache_expiry", default=10*60, help="cache timeout (seconds)", type=int)
    define("threads", default=1, help="number of threads to use for background IO", type=int)
    tornado.options.parse_command_line()
    
    pool = ThreadPoolExecutor(options.threads)
    
    config = Config()
    config.HTMLExporter.template_file = 'basic'
    config.NbconvertApp.fileext = 'html'
    config.CSSHTMLHeaderTransformer.enabled = False
    # don't strip the files prefix - we use it for redirects
    config.Exporter.filters = {'strip_files_prefix': lambda s: s}
    
    cache_urls = os.environ.get('MEMCACHE_SERVERS')
    if cache_urls:
        log.app_log.info("Using memecache")
        cache = AsyncMemcache(cache_urls.split(','), pool=pool)
    else:
        log.app_log.info("Using in-memory cache")
        cache = DummyAsyncCache()

    exporter = HTMLExporter(config=config)
    
    web.ErrorHandler = CustomErrorHandler
    template_path = pjoin(here, 'templates')
    static_path = pjoin(here, 'static')
    env = Environment(loader=FileSystemLoader(template_path))
    env.filters['markdown'] = markdown2html
    env.globals.update(nrhead=nrhead, nrfoot=nrfoot)
    client = AsyncHTTPClient()
    github_client = AsyncGitHubClient(client)
    github_client.authenticate()
    
    settings = dict(
        jinja2_env=env,
        static_path=static_path,
        client=client,
        github_client=github_client,
        exporter=exporter,
        cache=cache,
        cache_expiry=options.cache_expiry,
        pool=pool,
    )
    app = web.Application(handlers, **settings)
    http_server = httpserver.HTTPServer(app)
    log.app_log.info("Listening on port %i", options.port)
    http_server.listen(options.port)
    ioloop.IOLoop.instance().start()
    

if __name__ == '__main__':
    main()
@@ -1437,32 +1437,30 @@
     
-%22%22%22docstring for main%22%22%22
+# command-line options
 %0A   
@@ -1761,55 +1761,26 @@
     
-pool = ThreadPoolExecutor(options.threads)%0A    
+# NBConvert config
 %0A   
@@ -2071,24 +2071,143 @@
 s%7D%0A    %0A    
+exporter = HTMLExporter(config=config)%0A    %0A    # setup memcache%0A    pool = ThreadPoolExecutor(options.threads)%0A    mem
 cache_urls =
@@ -2230,17 +2230,19 @@
 'MEMCACH
-E
+IER
 _SERVERS
@@ -2242,16 +2242,65 @@
 SERVERS'
+,%0A        os.environ.get('MEMCACHE_SERVERS')%0A    
 )%0A    if
@@ -2300,16 +2300,19 @@
 %0A    if 
+mem
 cache_ur
@@ -2323,39 +2323,388 @@
         
-log.app_log.info(%22Using
+kwargs = dict(pool=pool)%0A        username = os.environ.get('MEMCACHIER_USERNAME', '')%0A        password = os.environ.get('MEMCACHIER_PASSWORD', '')%0A        if username and password:%0A            kwargs%5B'username'%5D = username%0A            kwargs%5B'password'%5D = password%0A            log.app_log.info(%22Using SASL memcache%22)%0A        else:%0A            log.app_log.info(%22Using plain
  memecac
@@ -2700,32 +2700,41 @@
 ain memecache%22)%0A
+        %0A
         cache = 
@@ -2747,16 +2747,19 @@
 emcache(
+mem
 cache_ur
@@ -2773,25 +2773,24 @@
 t(','), 
-pool=pool
+**kwargs
 )%0A    el
@@ -2881,51 +2881,54 @@
 e()%0A
+    
 %0A    
-exporter = HTMLExporter(config=config)
+# setup tornado handlers and settings
 %0A   
@@ -3580,24 +3580,60 @@
 pool,%0A    )%0A
+    %0A    # create and start the app%0A
     app = we
@@ -3879,16 +3879,16 @@
 ain__':%0A
-
     main
@@ -3885,12 +3885,13 @@
 :%0A    main()
+%0A

load memcachier config