import os
import cPickle

from quixote import get_request

from Defaults import *

from qommon.publisher import set_publisher_class, QommonPublisher

from root import RootDirectory
from admin import RootDirectory as AdminRootDirectory

from sessions import StorageSessionManager
from users import User

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

    supported_languages = ['fr']

    root_directory_class = RootDirectory
    admin_directory_class = AdminRootDirectory

    session_manager_class = StorageSessionManager
    user_class = User

    def get_application_static_files_root_url(self):
        return '%s/%s/' % (get_request().environ['SCRIPT_NAME'], WEB_ROOT)

    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)
        return True

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

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