"""Views for Interact application, which currently includes

- Landing : with three options for unauthenticated users (1) download zip or
            (2) authenticate and commence copying
- Progress : page containing live updates on server's progress, redirects to
             new content once pull or clone is complete
"""
from operator import xor

from tornado.web import RequestHandler
from tornado.options import options
from webargs import fields
from webargs.tornadoparser import use_args

from . import util
from .auth import HubAuth
from .download_file_and_redirect import download_file_and_redirect
from .pull_from_github import pull_from_github

url_args = {
    'file': fields.Str(),

    'repo': fields.Str(),
    'path': fields.List(fields.Str()),
}


class LandingHandler(RequestHandler):
    """
    Landing page containing option to download OR (exclusive) authenticate.

    Option 1
    --------

        ?file=public_file_url

    Example: ?file=http://localhost:8000/README.md

    Authenticates, then downloads file into user's system.

    Option 2
    --------

        ?repo=data8_github_repo_name&path=file_or_folder_name&path=other_folder

    Example: ?repo=textbook&path=notebooks&path=chapter1%2Fintroduction.md

    Authenticates, then pulls content into user's file system.
    Note: Only the gh-pages branch is pulled from Github.
    """
    @use_args(url_args)
    def get(self, args):
        is_file_request = ('file' in args)
        is_git_request = ('repo' in args and 'path' in args)
        valid_request = xor(is_file_request, is_git_request)
        if not valid_request:
            self.render('404.html')

        hubauth = HubAuth(options.config)
        # authenticate() returns either a username as a string or a redirect
        redirection = username = hubauth.authenticate()
        is_authenticated = isinstance(username, str)
        if not is_authenticated:
            values = []
            for k, v in args.items():
                if not isinstance(v, str):
                    v = '&path='.join(v)
                values.append('%s=%s' % (k, v))
            return self.render(
                'landing.html',
                authenticate_link=redirection.location,
                download_links=util.generate_git_download_link(args),
                query='&'.join(values))

        self.render(
            'progress.html',
            username=username,
            reusing_thread=False
        )

@@ -347,39 +347,160 @@
 xor%0A
-%0Afrom tornado.web import Reques
+from concurrent.futures import ThreadPoolExecutor%0A%0Afrom tornado import gen%0Afrom tornado.web import RequestHandler%0Afrom tornado.websocket import WebSocke
 tHan
@@ -771,16 +771,65 @@
 github%0A%0A
+thread_pool = ThreadPoolExecutor(max_workers=4)%0A%0A
 url_args
@@ -2626,8 +2626,632 @@
       )%0A
+%0A%0Aclass RequestHandler(WebSocketHandler):%0A    %22%22%22%0A    Handles the long-running websocket connection that the client makes after%0A    hitting the landing page.%0A%0A    This is where the important parts of the logic actually happen so we don't%0A    block the main thread.%0A    %22%22%22%0A    @gen.coroutine%0A    @use_args(url_args)%0A    def open(self, username, req_args):%0A        util.logger.info('%7B%7D: Websocket connected'.format(username))%0A        response = yield thread_pool.submit(sleep)%0A        util.logger.info(response)%0A%0A        self.write_message(%7B'hello': response%7D)%0A%0A%0Aimport time%0Adef sleep():%0A    time.sleep(5)%0A    return 'world'%0A

Add simple websocket handler that does async sleep