# -*- coding: utf8 -*-
'''
**********************************************
*      P R O T O C O L - C L A S S
*      for the biocase protocol
**********************************************
$RCSfile: base_response.py,v $
$Revision: 926 $
$Author: markus $
$Date: 2008-05-07 14:26:47 +0200 (Mi, 07. Mai 2008) $

Request and Response classes to support the biocase protocol.
'''

import types, sys, os
from xml.sax                            import parse, parseString
from cgi                                 import FieldStorage
from os.path                             import isfile
import xml.etree.ElementTree as ET
from biocase.tools.xmlutils              import prettyprint, cleanupNamespaces

import biocase.wrapper
from biocase.tools.various_functions        import isTrue
from biocase.wrapper.operations     import recordStatus
from biocase.wrapper.errorclasses        import *
from biocase.wrapper.protocol.BioCASe.biocase_handler    import requestHandler
from biocase.wrapper.protocol.base_request   import RequestBaseClass
from biocase.wrapper.sql.operators      import compressOperator

import biocase.configuration
cfg = biocase.configuration.Cfg()

import logging
log = logging.getLogger("pywrapper.protocol")


# ------------------------------------------------------------------------------------
class ResponseBaseClass:
    '''Response class implementing the essential methods used by the base protocol class'''

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    def __init__(self, dsaObj, diagnosticsHandler):
        # the datasource object (and through this also psfObj)
        self.dsaObj = dsaObj
        # the diagnostics handler that keeps track of all log.error and warnings. Useful to include diagnostics in responses
        self.diagnosticsHandler=diagnosticsHandler
        # the protocol xml document
        self.doc = None   # complete response xml document.
        # content only sub-tree of doc
        self.content = None
        
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    # HOOKS FOR THE SPECIFIC PROTOCOL NEEDS
    def postprocessMessage(self, requestObj, dbmodVersion):
        '''Filled request object that can be incorporated into a response if needed'''
        pass
    def getLogResultString(self):
        '''Short string used for result specific request logging in a 1-liner'''
        return ""


    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def printResponse(self, stream=sys.stdout, encoding='UTF-8', httpHeader=1):
        '''Returns a response as a string inserted into a stream.
        The parameter "httpHeader" is used to include a http header.
        '''
        if httpHeader > 0:
            header='Content-Type: text/xml\n\n'
            log.debug("Print http header: %s"%header)
            stream.write(header) # Blank line marking end of HTTP headers
        # clean document, push namespace declarations to the root element and assigne nice prefixes
        cleanupNamespaces(self.doc)
        # add copyright comment
        comment = ET.Comment("XML generated by BioCASE PyWrapper software version " +biocase.__version__ +". Made in Berlin.")        
        self.doc[0:0]=[comment]
        # print / return document
        if cfg.server.prettyprint:
            log.debug("Prettyprint response into stream %s"%str(stream))
            prettyprint(self.doc, stream=stream, encoding=encoding)
        else:
            log.debug("Write response into stream")
            stream.write(ET.tostring(self.doc, encoding))

    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def getPsfObj(self):
        return self.dsaObj.getPSFObj()
    psfObj = property(getPsfObj)
