'''Session and SessionManager objects. Configuration variables and utilities'''

from quixote import get_request

import qommon.sessions
from qommon.sessions import Session
from qommon.sessions import StorageSessionManager as SessionManager

from users import User
from hosts import Host

class BasicSession(Session):
    '''Session object. Configuration variables and utilities'''
    _names = 'sessions'

    users = {}
    lasso_session_dumps = {}
    provider_id = None

    def has_info(self):
        return self.users or self.lasso_session_dumps or self.provider_id or Session.has_info(self)
    is_dirty = has_info

    def get_user(self, provider_id=None):
        # Defaults to getting Larpe user.
        # It allows get_request().user to work in administration interface.
        if not provider_id:
            user_id = None
            host = Host.get_host_from_url()
            if not host:
                host = Host.select(lambda x: x.name == 'larpe')[0]
            if host:
                user_id = self.users.get(host.provider_id)
                if not user_id:
                    user_id = self.users.get(host.saml2_provider_id)
        else:
            user_id = self.users.get(provider_id)

        if user_id:
            try:
                user = User.get(user_id)
            except KeyError:
                user = User()
#            if str(user_id).startswith('anonymous-'):
                user.id = user_id
#                user.anonymous = True
#                if self.name_identifiers.has_key(providerId):
#                    if not user.name_identifiers.has_key(providerId):
#                        user.name_identifiers[providerId] = [ self.name_identifiers[providerId] ]

#                if self.name_identifiers.has_key(providerId):
#                    user.name_identifiers[providerId] = [ self.name_identifiers[providerId] ]
#                else:
#                    user.name_identifiers[providerId] = []
#                user.lasso_dumps[providerId] = self.lasso_anonymous_identity_dump
            return user
        return None

    def set_user(self, user_id, provider_id):
        self.users[provider_id] = user_id

class StorageSessionManager(SessionManager):
    '''SessionManager object. Subclass with multi-hosts specific features.'''
    def expire_session(self, provider_id=None):
        session = get_request().session
        if session.id is not None:
            if provider_id:
                if session.users.has_key(provider_id):
                    del session.users[provider_id]
                if session.lasso_session_dumps.has_key(provider_id):
                    del session.lasso_session_dumps[provider_id]
                session.store()
            if not session.users:
                SessionManager.expire_session(self)

qommon.sessions.BasicSession = BasicSession
