import os
import cPickle

from quixote import get_response, get_session, get_request

from Defaults import *

from qommon.publisher import set_publisher_class, QommonPublisher
from qommon import template

from root import RootDirectory
from admin import RootDirectory as AdminRootDirectory

from sessions import StorageSessionManager
from users import User
from hosts import Host

class LarpePublisher(QommonPublisher):
    APP_NAME = 'larpe'
    APP_DIR = APP_DIR
    DATA_DIR = DATA_DIR
    ERROR_LOG = ERROR_LOG
    WEB_ROOT = '/larpe'

    supported_languages = ['fr']

    root_directory_class = RootDirectory
    admin_directory_class = AdminRootDirectory

    session_manager_class = StorageSessionManager
    user_class = User

    def get_web_root_url(self):
        return get_request().environ['SCRIPT_NAME'] + WEB_ROOT + '/'

    def _get_user_name(self, host):
        user = get_session().get_user(host.provider_id)
        if user and user.name:
            return user.name
        return None

    def filter_output(self, request, output):
        response = get_response()
        if response.content_type != 'text/html':
            return output
        if not hasattr(response, 'filter') or not response.filter:
            return output
        
        org_name = 'Larpe'
        user_name = None
        host = Host.get_host_from_url()
        if host is not None:
            org_name = host.organization_name
        #    user_name = self._get_user_name(host)
        return template.decorate(output, response)

    def set_app_dir(self, request):
        self.app_dir = os.path.join(self.APP_DIR, request.get_server().lower().split(':')[0])
        self.reload_cfg()
        if self.cfg.has_key('proxy_hostname'):
            self.app_dir = os.path.join(self.APP_DIR, self.cfg['proxy_hostname'])
        if self.app_dir is not None and not os.path.exists(self.app_dir):
            os.mkdir(self.app_dir)

    cfg = None
    def write_cfg(self, directory=None):
        s = cPickle.dumps(self.cfg)
        if directory is None:
            directory = self.app_dir
        filename = os.path.join(directory, 'config.pck')
        open(filename, 'w').write(s)


set_publisher_class(LarpePublisher)
LarpePublisher.register_extra_dir(os.path.join(os.path.dirname(__file__), 'plugins', 'site_authentication'))

