#!/usr/bin/python

# COPYRIGHT (c) 2004-2007 Tijs van Dam <tijsvd at xs4all dot nl>

# 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

# The GNU General Public License can be found at:
#
#       http://www.gnu.org/licenses/gpl.txt
#

# Instructions:
# 
# Put this file in a CGI-executable directory, and make it executable
# by your webserver. Rename if necessary. For example, under Debian
# use the command (as root):
# 
#     install -m 755 anwb.py /usr/lib/cgi-bin/anwb
# 
# That should be all. Use a wap-browser to go to <http://your-server/cgi-bin/anwb>.


import urllib
import re
import sys
import cgi
import os

script = os.environ.get('SCRIPT_NAME')

re_file = re.compile(r'<a name="([an]\d+)"></a>\s*<b>(.*?)</b>\s*(.*?)</td>', re.I | re.S)
re_whitespace = re.compile(r'\s+')

re_geenmeldingen = re.compile(r'geen\s+filemelding', re.I)

def read_site():
    return urllib.urlopen(
       'http://www2.anwb.nl/verkeer/regioverkeerssituatie_overzichtallefiles_nl.nl.html'
	).read()


def parse_content(c):
    list = re_file.findall(c)
    dict = {}
    for (weg, text, km) in list:
        item = "%s %s" % (' '.join(re_whitespace.split(text)), km)
        try:
            dict[weg].append(item)
        except KeyError:
            dict[weg] = [item]

    if not dict and not re_geenmeldingen.search(c):
        raise Exception("parse error? empty dict")
        
    return dict

def sort_by_func(lst, f):
    decorated = [ (f(x), x) for x in lst ]
    decorated.sort()
    return [ x[1] for x in decorated ]

def sorted_keys(d):
    def order(w):
        if w[0] == 'A':
            try:
                return int(w[1:])
            except ValueError:
                return 200
        if w[0] == 'N':
            try:
                return int(w[1:]) + 100
            except ValueError:
                return 201
        return 300
    return sort_by_func(d, order)

def generate_wml_list(d, f):
    f.write('<wml><card title="Fileoverzicht">\n<p>')
    keys = sorted_keys(d)
    if keys:
        links = '<br/>\n'.join([ '<a href="%s?r=%s">%s</a>' 
                % (script, k, cgi.escape(k)) for k in keys ])
        f.write(links)
    else:
        f.write("Geen filemeldingen")
    f.write('\n</p></card></wml>')

def generate_wml_item(item, list, f):
    f.write('<wml><card title="%s">\n<p>' % item)
    f.write('<br/>\n'.join( [ cgi.escape(line) for line in list ] ) )
    f.write('\n</p><p><a href="%s">Terug</a></p></card></wml>' % script)
        

def handle_cgi_request():
    print "Content-Type: text/vnd.wap.wml"
    print "Cache-control: no-cache, must-revalidate"
    print "Pragma: no-cache"
    print
    print '<?xml version="1.0" ?>'
    print '<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">'

    try:
        content = read_site()
    except:
        print '<wml><card title="error"><p>Error connecting to ANWB</p></card></wml>'
        return

    try:
        d = parse_content(content)
    except Exception, err:
        print '<wml><card title="error"><p>Error: %s </p></card></wml>' % str(err)
        return


    f = cgi.FieldStorage()
    request = f.getfirst('r')
    if request:
        try:
            list = d[request]
        except KeyError:
            print '<wml><card title="%s"><p>Geen filemeldingen</p></card></wml>' % request
        else:
            generate_wml_item(request, list, sys.stdout)
    else:
        generate_wml_list(d, sys.stdout)

if __name__ == "__main__":
    handle_cgi_request()

