#
# This is a simple usable class for the 6pp project.
# (http://kvdb.net/projects/6pp/)
#
# Koen Bollen <meneer koenbollen nl>
# 2009 GPL
#

import urllib, urllib2
import socket
from xml.dom import minidom

class SIXPPIOError( Exception ):
    pass

class SIXPP( object ):
    """
    Retrieve information on a dutch postcode (zipcode).
    See http://kvdb.net/projects/6pp/ for more information.

    Example usage:
    >>> p = SIXPP( "5616JR" )
    >>> p.lookup()
    >>> print p.city
    Eindhoven
    >>> print p.street
    Jacobus Deckersstraat

    """

    url = "http://6pp.kvdb.net/lookup"


    def __init__(self, postcode, streetnumber=None, lookup=False ):
        """Construct the class, set the lookup parameter to True
        to automaticly call the lookup() method.
        """

        self.postcode, self.streetnumber = postcode, streetnumber

        if lookup:
            self.lookup()


    def lookup(self, timeout=None ):
        """Accually lookup the address."""

        args = {}
        args['postcode'] = self.postcode
        if self.streetnumber:
            args['streetnumber'] = self.streetnumber

        url = self.url + "?" + urllib.urlencode(args)

        if timeout:
            t = socket.getdefaulttimeout()
            socket.setdefaulttimeout( timeout )

        try:
            response = urllib2.urlopen( url )
        except:
            raise SIXPPIOError
        finally:
            if timeout:
                socket.setdefaulttimeout( t )

        rawdata = response.read()
        #print rawdata

        xml = minidom.parseString( rawdata )
        item = xml.getElementsByTagName("item")[0]
        for child in item.childNodes:
            self.__dict__[child.tagName] = child.firstChild.data


if __name__ == "__main__":
    import doctest
    doctest.testmod()


# vim: expandtab shiftwidth=4 softtabstop=4 textwidth=79:
