from qp.pub.publish import Publisher
from qp.pub.common import get_request, header, footer
from qp.fill.directory import Directory

class SitePublisher (Publisher):

    configuration = dict(
        http_address=('', 8001),
        as_https_address=('localhost', 9001),
        https_address=('localhost', 10001),
        scgi_address=('localhost', 11001),
	parse_xml=True,
        )

def page(title="Default Title", validate=True):
    def decorator(page_generator):
        def full_page(self, *args, **kwargs):
            from qp.pub.common import get_config_value
            xml = []
            xml.append(header(title))
            xml.append(page_generator(self, *args, **kwargs))
            xml.append(footer())
            page_text = "".join(xml)
            if get_config_value("parse_xml", False):
                from lxml import etree
                if not validate:
                    etree.fromstring(page_text)
                else:
                    parser = etree.XMLParser(dtd_validation=True)
                    etree.fromstring(page_text, parser)
                    if parser.error_log:
                        raise RuntimeError("Page failed to parse: " + str(parser.error_log))
	    return page_text
        return full_page
    return decorator

def fragment():
    def decorator(page_generator):
        def full_page(self, *args, **kwargs):
            from qp.pub.common import get_config_value
            from qpy import h8
            page_text = page_generator(self, *args, **kwargs) 
            if get_config_value("parse_xml", False):
                from lxml import etree
                doc = etree.fromstring(h8("<xml>") + page_text + h8("</xml>"))
	    return page_text
        return full_page
    return decorator


class SiteDirectory (Directory):
    """
    This site displays the http request.
    """

    def get_exports(self):
        yield 'good1', 'good1', None, None
        yield 'bad1', 'bad1', None, None
        yield 'good2', 'good2', None, None
        yield 'bad2', 'bad2', None, None

    @page("Good XHTML Test")
    def good1 [html] (self):
	"<p>Good XHTML Test</p>"

    @page("Bad XHTML Test")
    def bad1 [html] (self):
	"<B>Bad XHTML Test</B>"
 
    #--

    @fragment()
    def bad_fragment [html] (self):
        "<strong>Bad Fragment"

    @page("Bad XML Fragment Test")
    def bad2 [html] (self):
	self.bad_fragment()

    #--

    @fragment()
    def good_fragment [html] (self):
        "<p><strong>Good Fragment</strong></p>"

    @page("Good XML Fragment Test")
    def good2 [html] (self):
	self.good_fragment()
