# Copyright (C) 2002 John Goerzen
# <jgoerzen@complete.org>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

from __future__ import nested_scopes
import gpgme
import re

mapping = {}

class GPGMEError(Exception):
    def __init__(self, value = None):
        if value == None:
            self.value = ''
        else:
            self.value = value + ': '
    
    def getstring(self):
        return gpgme.gpgme_strerror(self.getvalue())

    def getvalue(self):
        raise NotImplementedError
    
    def __str__(self):
        return "%s%s (%d)" % (self.value, self.getstring(), self.getvalue())

for identifier in dir(gpgme):
    if not identifier.startswith('GPGME_'):
        continue
    if identifier == 'GPGME_EOF' or \
           (identifier.find('PROTOCOL') == -1 and \
           re.search('[a-z]', identifier)):
        # Error code.
        exec("""class %s(GPGMEError):
    def getvalue(self):
        return %s\n""" % \
             (identifier[6:], getattr(gpgme, identifier)))
        mapping[getattr(gpgme, identifier)] = globals()[identifier[6:]]

def errorcheck(retval, extradata = None):
    if retval != gpgme.GPGME_No_Error:
        raise mapping[retval], extradata

try:
    import xml.parsers.expat
    hasxml = 1
except ImportError:
    hasxml = 0

if not hasxml:
    def getXMLval(value, str):
        """Your system does not have xml.parsers.expat installed, so
        this function will not provide accurate results.  It will
        always just return [] until you install that module."""
        return []
else:    
    def getXMLval(value, str):
        """Looks up a particular value in XML output.  For instance, given
        this:

<GnupgOperationInfo>
  <encryption>
    <error>
      <invalidRecipient/>
      <reason>0</reason>
      <name>User Name</name>
    </error>
  </encryption>
</GnupgOperationInfo>

        You might call:

        getXMLval('/GnupgOperationInfo/encryption/error/name', errstr)

        and you'll get ["User Name"] returned.

        If more than one value matches, you'll get a list of each
        matching value.

        [] is returned if there are no matches.
        """

        value = '/DOC' + value

        class ParseHandler:
            def __init__(self, lookfor):
                self.whereami = ''
                self.lookfor = lookfor
                self.retval = []

            def start_element(self, name, attrs):
                self.whereami += '/' + name

            def char_data(self, data):
                if self.whereami == self.lookfor:
                    self.retval.append(data)

            def end_element(self, name):
                self.whereami = '/'.join(self.whereami.split('/')[:-1])

        ph = ParseHandler(value)
        p = xml.parsers.expat.ParserCreate()
        p.StartElementHandler = ph.start_element
        p.EndElementHandler = ph.end_element
        p.CharacterDataHandler = ph.char_data

        p.returns_unicode = 0
        p.Parse("<DOC>\n" + str + "\n</DOC>\n")

        return ph.retval
    
