"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/common.py $
$Id: common.py 27879 2006-01-26 20:36:16Z dbinger $
"""
import os
import sys
from cStringIO import StringIO
from qp.pub.common import get_publisher
from qp.lib.site import Site
from sancho.utest import UTest
import dulcinea

if os.environ.get('SITE') in Site.get_sites():
    Site(os.environ.get('SITE')).get_publisher()

if get_publisher() is None:
    from dulcinea.site_util import SiteModule
    dulcinea.local = SiteModule()
    sys.modules['dulcinea.local'] = dulcinea.local
    from quixote.ptl import install
    _used = install
    def is_qp():
        return False
    def get_site_name():
        site = os.environ.get('SITE', 'test')
        return site
    import quixote.publish
    from qp.lib.util import import_object
    from dulcinea.site_util import get_config_value, parse_address, is_live
    from durus.client_storage import ClientStorage
    from durus.file_storage import FileStorage
    from durus.connection import Connection

    def create_publisher(config=None, file=None):
        publisher = quixote.publish.get_publisher()
        if publisher:
            assert config is None
            assert file is None
            return publisher
        if get_site_name() == 'test':
            publisher_class_name = 'dulcinea.ui.publisher.DulcineaPublisher'
            import dulcinea.test.local
            connection = dulcinea.test.local.make_test_connection()
        else:
            publisher_class_name = get_config_value(
                'publisher', site=get_site_name(),
                fallback='dulcinea.ui.publisher.DulcineaPublisher')
            if file is None:
                durus_address = get_config_value('durus_address',
                site=get_site_name())
                host, port = parse_address(durus_address)
                storage = ClientStorage(port=port, host=host)
            else:
                storage = FileStorage(file)
            connection = Connection(storage=storage)
        return import_object(publisher_class_name)(
            connection=connection, config=config)
    def get_publisher():
        return create_publisher()
    def open_connection(filename):
        assert quixote.publish.get_publisher() is None
        return create_publisher(file=filename).get_connection()
    def clear_publisher():
        quixote.publish._publisher = None
    from quixote import get_field, redirect, get_path, get_session
    from quixote import get_request, get_user, get_response
    from quixote.directory import Directory
    from quixote.form.css import BASIC_FORM_CSS
    from quixote.form.form import Form
    from quixote.form.widget import MultipleSelectWidget, ButtonWidget
    from quixote.form.widget import NumberWidget, FloatWidget, IntWidget
    from quixote.form.widget import OptionSelectWidget, CompositeWidget
    from quixote.form.widget import SingleSelectWidget, RadiobuttonsWidget
    from quixote.form.widget import StringWidget, FileWidget, PasswordWidget
    from quixote.form.widget import SubmitWidget, ResetWidget, HiddenWidget
    from quixote.form.widget import TextWidget, CheckboxWidget, SelectWidget
    from quixote.form.widget import WidgetList, WidgetDict, subname, Widget
    from quixote.form.widget import WidgetValueError
    from quixote.html import htmltag, href, url_quote, nl2br
    from quixote.html import stringify, htmltext, htmlescape
    from quixote.html import url_with_query
    from quixote.util import FileStream
    from quixote.util import get_directory_path


    def set_test_environment(input_string='', **env):
        env.setdefault('SCRIPT_NAME', '')
        env.setdefault('PATH_INFO', '/')
        from quixote.http_request import HTTPRequest
        from quixote.logger import DefaultLogger
        import sys
        def __init__(self, **kwargs):
            self.error_log = sys.stdout
            self.access_log = None
            self.error_email = None
        DefaultLogger.__init__ = __init__
        quixote.publish._publisher = None
        publisher = get_publisher()
        publisher._set_request(HTTPRequest(StringIO(input_string), env))
        get_request().session = publisher.session_manager._create_session()
        def nothing(*args):
            pass
        publisher.abort = nothing
        publisher.commit = nothing
        publisher._clear_request = nothing
        quixote.publish._publisher = publisher

    class CommonTest (UTest):

        def _pre(self):
            UTest._pre(self)
            site = get_site_name()
            assert site in (None, 'test') or not is_live(site)
            set_test_environment()

        def _post(self):
            UTest._post(self)
            quixote.publish._publisher = None

    from dulcinea.sendmail import sendmail


else:
    print "\nDulcinea QP"
    def is_qp():
        return True
    import dulcinea.uiqp
    import sys
    sys.modules['dulcinea.ui'] = dulcinea.uiqp
    dulcinea.ui = dulcinea.uiqp
    def get_site_name():
        return get_publisher().get_site().get_name()
    from qpy import stringify, h8
    htmltext = h8
    htmlescape = h8.quote
    from qp.fill.html import htmltag, href, nl2br, url_quote, url_with_query
    from qp.pub.common import get_request, get_user, get_response
    from qp.pub.common import redirect, get_path, get_session
    def get_field(x):
        return get_request().get_field(x)
    from qp.fill.css import BASIC_FORM_CSS
    from qp.fill.directory import Directory, get_directory_path
    from qp.fill.form import Form
    from qp.fill.static import FileStream
    from qp.fill.widget import MultipleSelectWidget, ButtonWidget
    from qp.fill.widget import NumberWidget, FloatWidget, IntWidget
    from qp.fill.widget import OptionSelectWidget, CompositeWidget
    from qp.fill.widget import SingleSelectWidget, RadiobuttonsWidget
    from qp.fill.widget import StringWidget, FileWidget, PasswordWidget
    from qp.fill.widget import SubmitWidget, ResetWidget, HiddenWidget
    from qp.fill.widget import TextWidget, CheckboxWidget, SelectWidget
    from qp.fill.widget import WidgetList, WidgetDict, subname, Widget
    from qp.fill.widget import WidgetValueError
    from qp.pub.common import header, page

    def set_test_environment(input_string='', **env):
        env.setdefault('SCRIPT_NAME', '')
        env.setdefault('PATH_INFO', '/')
        from qp.pub.hit import Hit
        hit = Hit(StringIO(input_string), env)
        publisher = get_publisher()
        publisher.set_hit(hit)
        def nothing(*args):
            pass
        publisher.abort = nothing
        publisher.commit = nothing

    class CommonTest (UTest):

        def _pre(self):
            set_test_environment()

    from qp.mail.send import sendmail
    import dulcinea
    dulcinea.local = get_publisher()
    sys.modules['dulcinea.local'] = dulcinea.local


def header(title, *args, **kwargs):
    return get_publisher().header(title, *args, **kwargs)

def page(title, *content, **kwargs):
    return get_publisher().page(title, *content, **kwargs)

def footer(*args, **kwargs):
    return get_publisher().footer(*args, **kwargs)

def not_found(*args, **kwargs):
    return get_publisher().not_found(*args, **kwargs)

def access_denied(body=None):
    return get_publisher().respond('Access Denied',
        body or 'That is not currently allowed.', status=403)

def invalid_query(body='Unable to answer that query.'):
    return get_publisher().respond('Invalid Query',
        body or 'Unable to answer that query.', status=400)

def format_user(user, **kwargs):
    return get_publisher().format_user(user, **kwargs)

def format_user_profile(user):
    return get_publisher().format_user_profile(user)

def format_date(date):
    return get_publisher().format_date(date)

def format_date_time(date):
    return get_publisher().format_date_time(date)

def format_login_agreement():
    return get_publisher().format_login_agreement()

def get_feedback_domain():
    return get_publisher().get_feedback_domain()

def get_feedback_addresses():
    return get_publisher().get_feedback_addresses()

def get_user_db():
    return get_publisher().get_user_db()

def get_site_title():
    return get_publisher().get_site_title()

def get_connection():
    return get_publisher().get_connection()


_used = [get_publisher, stringify, htmltext, htmlescape, htmltag, href,
         url_quote, nl2br, url_with_query, get_request, get_user, get_response,
         get_field, redirect, get_path, get_session,
         Form, StringWidget, FileWidget, PasswordWidget, TextWidget,
         CheckboxWidget, SelectWidget, SingleSelectWidget, RadiobuttonsWidget,
         MultipleSelectWidget, ButtonWidget, SubmitWidget, ResetWidget,
         HiddenWidget, NumberWidget, FloatWidget, IntWidget,
         OptionSelectWidget, CompositeWidget, WidgetList, WidgetDict,
         subname, Widget, WidgetValueError, FileStream, Directory,
         get_directory_path, header, footer, page,
         format_user, format_user_profile, format_date, format_date_time,
         format_login_agreement, get_feedback_domain, get_feedback_addresses,
         BASIC_FORM_CSS, CommonTest, sendmail, get_user_db]


