# Copyright 2015 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
import json
import logging
import os
import pkg_resources

from pyramid.httpexceptions import HTTPNotFound
from pyramid.response import FileResponse
from pyramid.view import view_config


ASSET_PATH = os.path.join(
    os.path.dirname(__file__),
    'static',
    'gui',
    'build',
    'app'
    )


VERSION = pkg_resources.get_distribution('jujugui').version
log = logging.getLogger('jujugui')


@view_config(
    route_name='jujugui.app',
    renderer='jujugui:templates/index.html.mako',
    http_cache=3600 * 24 * 365)
def app(request):
    """The main Juju GUI JavaScript application."""
    env_uuid = request.matchdict.get('uuid')
    settings = request.registry.settings
    cache_buster = settings.get('jujugui.cachebuster', VERSION)
    # kadams54, 2016-02-01: per https://github.com/juju/juju-gui/issues/1299
    is_standalone = request.domain != 'demo.jujucharms.com'
    logo_url = '' if is_standalone else 'http://jujucharms.com/'

    return {
        'config_url': request.route_path('jujugui.config', uuid=env_uuid),
        'convoy_url': request.route_path(
            'jujugui.convoy', cachebuster=cache_buster, uuid=env_uuid),
        'combine': settings['jujugui.combine'],
        'logo_url': logo_url,
        'raw': settings['jujugui.raw'],
    }


@view_config(route_name='jujugui.ui')
def juju_ui(request):
    requested_file = request.matchdict.get('file')
    file_path = os.path.join(ASSET_PATH, requested_file)
    try:
        return FileResponse(file_path, request=request)
    except OSError:
        log.info('No such file: %s' % file_path)
        return HTTPNotFound()


@view_config(route_name='jujugui.config', renderer='string')
def config(request):
    """The Juju GUI dynamically generated config.js file.

    This file includes the GUI configuration options, including the Juju API
    configuration.
    """
    settings = request.registry.settings
    request.response.content_type = 'application/javascript'
    sandbox_enabled = settings['jujugui.sandbox']

    user = settings.get('jujugui.user')
    password = settings.get('jujugui.password')
    base_url = settings.get('jujugui.base_url')
    env_uuid = settings.get('jujugui.uuid', 'sandbox')

    if sandbox_enabled:
        user = user if user is not None else 'admin'
        password = password if password is not None else 'password'

    if settings.get('jujugui.insecure', False):
        socket_protocol = 'ws'
    else:
        socket_protocol = 'wss'

    options = {
        # Base YUI options.
        'auth': settings['jujugui.auth'],
        'serverRouting': False,
        'html5': True,
        'container': '#main',
        'viewContainer': '#main',
        'baseUrl': base_url,
        'transitions': False,
        'cachedFonts': False,
        # Debugging options.
        'consoleEnabled': True,
        'simulateEvents': False,
        # The charm store URL and path.
        'charmstoreURL': settings['jujugui.charmstore_url'],
        'charmstoreAPIPath': settings['jujugui.charmstore_api_path'],
        # The jem url and path.
        'jemURL': settings['jujugui.jem_url'],
        'jemAPIPath': settings['jujugui.jem_api_path'],
        # WebSocket connection to the Juju API.
        'socket_protocol': socket_protocol,
        'user': user,
        'password': password,
        'jujuEnvUUID': env_uuid,
        'interactiveLogin': settings['jujugui.interactive_login'],
        # Enable/disable sandbox (demonstration) mode.
        'sandbox': sandbox_enabled,
        'sandboxSocketURL': 'wss://demo.jujucharms.com/ws',
        # XXX frankban: do we still support read-only mode?
        'readOnly': False,
        # Set the GTM_enabled to enable Google Tag Manager usage and calls.
        # Also implies using cookies.
        'GTM_enabled': settings['jujugui.GTM_enabled'],
        # Set a juju-core version so the GUI can adapt its available features.
        'jujuCoreVersion': settings.get('jujugui.jujuCoreVersion', ''),
        'apiAddress': settings.get('jujugui.apiAddress', ''),
        'socketTemplate': settings['jujugui.socketTemplate'],
    }
    return 'var juju_config = {};'.format(json.dumps(options))


@view_config(route_name='jujugui.version', renderer='prettyjson')
def version(request):
    return {'version': VERSION}

@@ -2332,16 +2332,147 @@
 dbox')%0A%0A
+    jem_macaroons = settings.get('jujugui.jem_macaroons')%0A    charmstore_macaroons = settings.get('jujugui.charmstore_macaroons')%0A%0A
     if s
@@ -3417,32 +3417,158 @@
 jem_api_path'%5D,%0A
+        # Any provided macaroons.%0A        'charmstoreMacaroons': charmstore_macaroons,%0A        'jemMacaroons': jem_macaroons,%0A
         # WebSoc

Add macaroons to config if provided