import os

from quixote import get_response, get_session, get_publisher
from quixote.directory import Directory, AccessControlled

from qommon import errors
from qommon import get_logger

from identities import IdentitiesDirectory
from settings import SettingsDirectory
from debug import DebugDirectory
from logger import LoggerDirectory

from authentic import identities


def gpl [html] ():
    """<p>This program is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by the Free
    Software Foundation; either version 2 of the License, or (at your option)
    any later version.</p>

    <p>This program is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    for more details.</p>

    <p>You should have received a copy of the GNU General Public License along with
    this program; if not, write to the Free Software Foundation, Inc., 59 Temple
    Place - Suite 330, Boston, MA  02111-1307, USA.</p>
    """


class RootDirectory(AccessControlled, Directory):

    _q_exports = ['', 'identities', 'settings', 'debug', 'logger']

    identities = IdentitiesDirectory()
    settings = SettingsDirectory()
    debug = DebugDirectory()
    logger = LoggerDirectory()

    menu_items = [
        ('identities/', N_('Identity Management')),
        ('logger/', N_('Logs')),
        ('settings/', N_('Settings')),
        ('debug/', N_('Debug')),
        ('/', N_('Authentic Identity Server'))]

    def _q_access(self):
        get_response().breadcrumb.append( ('admin/', _('Administration')) )

        session = get_session()
        try:
            identities.get_store().load_identities()
        # FIXME : The following line doesn't work anymore, for an unknown reason, but should work :
        #except identities.IdentityStoreException, e:
        except Exception, e:
            get_logger().error(str(e))
            if os.path.exists(os.path.join(get_publisher().app_dir, 'emergency')):
                return
            # XXX: raise a 'server problem; try later' to display such a page
            raise errors.AccessForbiddenError(e)

        try:
            identities.get_store().connect(session)
        except Exception, e:
            get_logger().error(str(e))
        try:
            if identities.get_store().is_bootstrapping():
                return
        except identities.IdentityStoreException, e:
            get_logger().error(str(e))

        if not session or session.user is None:
            if os.path.exists(os.path.join(get_publisher().app_dir, 'emergency')):
                return
            raise errors.AccessUnauthorizedError()
        try:
            identity = identities.get_store().get_identity(session.user)
        except KeyError:
            identity = None
        except identities.IdentityStoreException, e:
            get_logger().error(str(e))
            if os.path.exists(os.path.join(get_publisher().app_dir, 'emergency')):
                return
            identity = None

        if not identity or not identity.is_admin():
            if os.path.exists(os.path.join(get_publisher().app_dir, 'emergency')):
                return
            raise errors.AccessForbiddenError()

    def _q_index [html] (self):
        from menu import html_top, get_vc_version
        html_top('/')
        '<p>'
        _('''Authentic is a Liberty-compliant identity provider aiming to
address a broad range of needs, from simple to complex setups. Its Liberty
compliance relies on Lasso, a free (GNU GPL) implementation of the Liberty
Alliance specifications.''')
        '</p>'
        '<p>'
        _('''Authentic itself is licensed under the terms of the GNU General
Public License.''')
        '</p>'
        version = get_vc_version()
        if version:
            '<p class="version-info">'
            _('Version:')
            ' '
            version

        doc_url = 'http://authentic.labs.libre-entreprise.org/doc/%s' % \
                _('en/authentic-admin.html')

        '<p>'
        _('For more information:')
        '</p>'

        '<ul>'
        '<li><a href="http://authentic.labs.libre-entreprise.org">%s</a></li>' % _('Web site')
        '<li><a href="%s">%s</a></li>' % (doc_url, _('Online documentation'))
        '</ul>'

        get_response().filter['sidebar'] = str(self.get_sidebar())

    def get_sidebar [html] (self):
        return gpl()


def register_page(url_name, directory = None, label = None):
    first_time = False
    if not url_name in RootDirectory._q_exports:
        RootDirectory._q_exports.append(url_name)
        first_time = True

    if directory:
        setattr(RootDirectory, url_name, directory)
    if not label:
        label = directory.label

    if first_time:
        logger_index = RootDirectory.menu_items.index(('logger/', 'Logs'))
        if directory:
            url_name += '/'
        RootDirectory.menu_items.insert(logger_index, (url_name, label))

