# Copyright (c) 2001 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
# 
# 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, 

from narval.lib import select_many, select_one, AL_NS, NO_NS, get_encoding
import md5

MOD_XML = """<?xml version="1.0" encoding="ISO-8859-1"?>
<module name='Checksum' xmlns:al='%s'>""" % AL_NS

    
MOD_XML = MOD_XML + """
<al:action name='md5_checksum' func='md5_checksum_f'>
<al:description lang='en'>compute a md5 checksum on raw data</al:description>
<al:input id='input'  outdates='yes' list='yes'><al:match>data-unit[data/text()]</al:match>
<al:description lang='en'>data-unit element with data child containing text to hash
</al:description></al:input>
<al:output id='output'  list='yes'><al:match>data-unit[@md5checksum]</al:match>
<al:description lang='en'>data-unit element with new/updated md5checksum attribut
</al:description></al:output>
</al:action>
"""
def md5_checksum_f(args, doc):
    from xml.dom.ext import PrettyPrint
    outputs = {'output': []}
    for node in args['input']:
        data = select_one(node,'data/text()').data
        m = md5.new(data.encode(get_encoding()))
        new_digest = repr(m.digest())
##        print "None:[%s] '':[%s]"%(node.getAttributeNS(NO_NS, 'md5checksum'),
##                                   node.getAttributeNS('', 'md5checksum'))
        node.removeAttributeNS(NO_NS, 'md5checksum')
        node.removeAttributeNS('', 'md5checksum')
        node.setAttributeNS(NO_NS, 'md5checksum', new_digest)
##        print '%'*80
        outputs['output'].append(node)
        ##PrettyPrint(node)
    return outputs


# Test #########################################################################

MOD_XML = MOD_XML + "</module>"

if __name__ == "__main__" :
    from xml.dom.ext.reader import Sax2
    print MOD_XML
    doc=Sax2.FromXml(MOD_XML)
    print doc.documentElement
