import os
import httplib

import lasso

from quixote import get_request, get_response, get_session, redirect
from quixote.directory import Directory

from qommon.form import *
from qommon import template

import admin
import liberty_root
import errors

from hosts import Host
from users import User
from Defaults import WEB_ROOT

class RootDirectory(Directory):
    _q_exports = ['', 'admin', 'liberty', 'token']

    admin = admin.RootDirectory()
    liberty = liberty_root.LibertyRootDirectory()

    def _q_index [html] (self):
        template.html_top(_('Welcome to Larpe reverse proxy'))
        '<ul><li><a href="%s/admin/">%s</a></li></ul>' % (get_request().environ['SCRIPT_NAME'],
                                                         _('Configure Larpe'))

    def _q_traverse(self, path):
        response = get_response()
        response.filter = {}

        return Directory._q_traverse(self, path)

    def _q_lookup(self, component):
        return redirect(component + '/')

    def token [html] (self):
        session = get_session()

        if not hasattr(session, str('name_identifier')) or not session.name_identifier \
                or not hasattr(session, str('lasso_dump')) or not session.lasso_dump:
            raise errors.AccessUnauthorizedError()

        # If the token is in the query string, use it
        query_string = get_request().get_query()
        if query_string:
            parameters = query_string.split(str('&'))
            for param in parameters:
                values = param.split(str('='))
                if len(values) < 2:
                    continue
                if values[0] == str('token'):
                    return self._federate_token(values[1])

        # Otherwise, display a form to ask for the token
        form = Form(enctype='multipart/form-data')
        form.add(StringWidget, 'token', title = _('Identification Token'),
                required = True, size = 30)
        form.add_submit('submit', _('Submit'))
        form.add_submit('cancel', _('Cancel'))

        if form.get_widget('cancel').parse():
            return redirect('.')

        if not form.is_submitted() or form.has_errors():
            template.html_top(_('Identification Token'))
            '<p>'
            _('Please enter your identification token. ')
            _('Your local account will be federated with your Liberty Alliance account.')
            '</p>'
            form.render()
        else:
            session = get_session()

            if not hasattr(session, str('name_identifier')) or not session.name_identifier \
                    or not hasattr(session, str('lasso_dump')) or not session.lasso_dump:
                raise errors.AccessUnauthorizedError()

            token = form.get_widget('token').parse()

            return self._federate_token(token)

    def _federate_token(self, token):
        session = get_session()

        # Get the user who owns this token    
        users_with_token = list(User.select(lambda x: x.identification_token == token))
        if len(users_with_token) == 0:
            return template.error_page(_('Unknown Token'))

        # Fill user attributes
        user = users_with_token[0]
        user.name_identifiers.append(session.name_identifier)
        user.lasso_dumps = [ session.lasso_dump ]
        user.identification_token = None
        user.is_admin = True
        user.store()

        # Set this user in the session
        session.set_user(user.id, session.provider_id)

        # Delete now useless session attributes
        del session.name_identifier
        del session.lasso_dump
        del session.provider_id

        return redirect('%s/admin/' % get_request().environ['SCRIPT_NAME'])

