import os

import lasso

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

from qommon.admin.menu import html_top
from qommon.admin import logger

from larpe import errors
from larpe import misc

import hosts
import users
import settings

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 = ['', 'hosts', 'users', 'settings', 'logger']

    hosts = hosts.HostsDirectory()
    users = users.UsersDirectory()
    settings = settings.SettingsDirectory()
    logger = logger.LoggerDirectory()

    menu_items = [
        ('hosts/', N_('Hosts')),
        ('users/', N_('Users')),
        ('settings/', N_('Settings')),
        ('logger/', N_('Logs')),
        ('/', N_('Liberty Alliance Reverse Proxy'))]

    def _q_access(self):
        # FIXME : this block should be moved somewhere else
        get_publisher().reload_cfg()
        if not get_publisher().cfg.has_key('proxy_hostname'):
            get_publisher().cfg['proxy_hostname'] = get_request().get_server().split(':')[0]
        get_publisher().write_cfg()

        response = get_response()
        if not hasattr(response, 'breadcrumb'):
            response.breadcrumb = [ ('../admin/', _('Administration')) ]

        # Cheater
        if os.path.exists(os.path.join(get_publisher().app_dir, 'ADMIN_FOR_ALL')):
            return

        # No admin user created yet, free access
        user_list = users.User.select(lambda x: x.is_admin)
        if not user_list:
            return

        host_list = hosts.Host.select(lambda x: x.name == 'larpe')
        if host_list:
            host = host_list[0]
        else:
            raise errors.AccessForbiddenError()

        if misc.get_current_protocol() == lasso.PROTOCOL_SAML_2_0:
            user = get_session().get_user(host.saml2_provider_id)
        else:
            user = get_session().get_user(host.provider_id)
        if user:
            if not user.name or not user.is_admin:
                raise errors.AccessForbiddenError()
        else:
            raise errors.AccessUnauthorizedError()


    def _q_index [html] (self):
        html_top('')
        gpl()

