import sys
import random

from quixote import get_publisher, get_response, redirect, get_request
from quixote.directory import Directory
from quixote.errors import TraversalError

import lasso

import admin
import liberty
import saml2
import idwsf2
import httplib
import urllib

from qommon.form import *
from qommon.misc import get_abs_path, get_current_protocol
from qommon import template, get_logger

import errors
import misc

from users import User
from hosts import Host

class LibertySite(Directory):

    _q_exports = ['', 'login', 'logout', 'liberty', 'saml', 'idwsf2']

    liberty = liberty.Liberty()
    saml = saml2.Saml2()
    idwsf2 = idwsf2.IdWsf2()

    def __init__(self, component):
        self.name = component

    def _q_index (self):
        raise errors.TraversalError()

    def login [html] (self):
        get_logger().info('login')
        get_publisher().reload_cfg()

        if not get_publisher().cfg.has_key('idp'):
            return template.error_page(_('SSO support is not yet configured'))
        else:
            server = misc.get_lasso_server('liberty')
            if server is not None:
                return self.liberty.perform_login()

            server = misc.get_lasso_server('saml2')
            if server is not None:
                return self.saml.perform_login()

            return template.error_page(_('SSO support is not yet configured'))

    def logout(self):
        get_logger().info('logout')
        session = get_session()
        if not session:
            return redirect('%s/' % get_request().environ['SCRIPT_NAME'])

        if misc.get_current_protocol() == lasso.PROTOCOL_SAML_2_0:
            return self.saml.slo_sp()
        else:
            return self.liberty.singleLogout()

