from __future__ import absolute_import

import logging
log = logging.getLogger(__name__)

import os
import uuid

from flask import (
    render_template, request, send_from_directory,
    abort, jsonify, Response, redirect, url_for
)
from six import string_types

from bokeh import protocol
from bokeh.exceptions import DataIntegrityException
from bokeh.resources import Resources
from bokeh.templates import AUTOLOAD

from .bbauth import handle_auth_error
from ..app import bokeh_app
from ..crossdomain import crossdomain
from ..models import docs
from ..models import user
from ..serverbb import prune, BokehServerTransaction, get_temporary_docid
from ..views import make_json
from ..views.decorators import login_required
from ..settings import settings as server_settings

def request_resources():
    """Creates resources instance based on url info from
    current app/request context
    """
    if bokeh_app.url_prefix:
        # strip of leading slash
        root_url  = request.url_root + bokeh_app.url_prefix[1:]
    else:
        root_url  = request.url_root
    resources = Resources(root_url=root_url, mode='server')
    return resources

def render(fname, **kwargs):
    resources = request_resources()
    bokeh_prefix = resources.root_url
    return render_template(fname, bokeh_prefix=bokeh_prefix,
                           **kwargs)

@bokeh_app.route('/bokeh/ping')
def ping():
    ''' Test whether Bokeh server is up.

    :status 200:

    '''
    # test route, to know if the server is up
    return "pong"

@bokeh_app.route('/')
@bokeh_app.route('/bokeh/')
def index(*unused_all, **kwargs):
    ''' Render main page.

    :status 200: if current user logged in
    :status 302: otherwise redirect to login

    '''
    bokehuser = bokeh_app.current_user()
    if not bokehuser:
        return redirect(url_for('.login_get'))
    return render('bokeh.html',
                  splitjs=server_settings.splitjs,
                  username=bokehuser.username,
                  title="Bokeh Documents for %s" % bokehuser.username
    )

@bokeh_app.route('/bokeh/favicon.ico')
def favicon():
    ''' Return favicon.

    :status 200: return favicon

    '''
    return send_from_directory(os.path.join(bokeh_app.root_path, 'static'),
                               'favicon.ico', mimetype='image/x-icon')

def _makedoc(redisconn, u, title):
    docid = str(uuid.uuid4())