"""Module containing the XML related functionality for the search service.
"""

# adjust to test environment
try:
    import rr_util
except ImportError:
    import test_util
    pass
#
###


class SearchResult ( object ):
    """Class describing the result set of a search.

    The class holds a list of resource descriptions which are
    converted to the proper XML structure on the fly.
    """


    _result_template = u'''<?xml version="1.0" encoding="%(encoding)s"?>
<search-result xmlns="http://www.infrae.com/namespaces/search">
  <request>%(request_url)s</request>
  <size>%(result_size)d</size>
  <resources>
%(resources)s
  </resources>
</search-result>
'''

    _resource_template = u'''
    <resource>
      <url>%(resource_url)s</url>
      <mime-type>%(resource_type)s</mime-type>
      <size>%(resource_size)d</size>
      <lastmodified>%(resource_date)s</lastmodified>
    </resource>
'''


    def __init__ ( self, request ):
        self._resources = []
        self._request = request
        return

    def append_resource ( self, resource ):
        """Append a resource description to the result set.

        The resource descriptions are dict with the following keys:
          resource_id  : the unique id of the resource
          resource_url : the download url of this resource
          resource_type: the mime-type of the resource
          resource_size: the size of the resource in bytes
          resource_date: the date this resource was last modified
        """
        self._resources.append(resource)
        return

    def as_string ( self, encoding='utf-8' ):
        """Return the current result-set as xml string encoded with
        the given encoding.
        """
        ret = self._create_result(encoding)
        return ret

    def _create_result ( self, encoding ):
        # build list of xml strings holding the resource descriptions
        rl = []
        for r in self._resources:
            s = self._resource_template % r
            rl.append(s)
        res_str = u''.join(rl)
        # prepare outer part of response
        d = {}
        d['encoding'] = encoding
        d['request_url'] = self._request
        d['result_size'] = len(rl)
        d['resources'] = res_str
        xml = self._result_template % d
        # encode and return result
        return xml.encode(encoding)
        
#
###
