#!/usr/bin/perl
#
# street2wp.pl by Stefan Tomanek <stefan@pico.ruhr.de>
#
# Converts german adresses to GpsDrive waypoints

use WWW::Mechanize;
# use HTML::Entities;
use Unicode::String qw(utf8 latin1);
use DBI();

sub connect_db {
    my $host = "localhost";
    my $user = "gast";
    my $password = "gast";
    my $database = "geoinfo";
    return DBI->connect("DBI:mysql:database=$database;host=$host", $user, $password, {'RaiseError' => 1});
}

sub insert_wp($$) {
    my ($db, $wp) = @_;
    
    my $sth = $db->prepare('DELETE FROM waypoints WHERE comment=? AND type="HOUSE"');
    
    $sth->execute($wp->{comment});
    $sth->finish();
    
    my $sth2 = $db->prepare( 'INSERT INTO waypoints (name, type, lat, lon, comment) VALUES (?, "HOUSE", ?, ?, ?);' );
    $sth2->execute($wp->{name}, $wp->{lat}, $wp->{long}, $wp->{comment});
    $sth2->finish();
}

sub get_map($$$$) {
    my ($name, $street, $city, $zip) = @_;

    $name =~ s/ /_/g;
    
    my $uname = latin1($name)->utf8();
    
    $street =~ s/ä/ae/ig;
    $street =~ s/ö/oe/ig;
    $street =~ s/ü/ue/ig;
    $street =~ s/ß/ss/ig;
    
    my $db = connect_db();
    my $mech = WWW::Mechanize->new();
    my $url = "http://www.multimap.com/map/home.cgi?client=public&lang=&advanced=&db=DE";
    $mech->get( $url );
    
    $mech->submit_form(
	form_name   => "search",
	fields      => {
			addr2    => $street,
			addr3    => $city,
			pc       => $zip
			}
	);
    my $page = $mech->content();
    
    if ($page =~ /<meta name="geo\.position" content="([0-9.]+);([0-9.]+)" \/>/) {
	my %wp = ( name    => $uname,
	           lat     => $1,
		   long    => $2,
		   comment => "$zip $city, $street"
		  );
	# print $wp{lat}." ".$wp{long};
	insert_wp($db, \%wp);
    }
    
    $db->disconnect();
}

sub read_csv() {
    while (<STDIN>) {
	if (/^(.+?);(.+?);(.+?);(\d{5})$/) {
	    my ($name, $street, $city, $zip) = ($1, $2, $3, $4);
	    print "Adding: $name, $street, $city, $zip...";
	    get_map($name, $street, $city, $zip);
	    print "done\n";
	}
    }
}

if (defined $ARGV[0] && $ARGV[1] && $ARGV[2] && $ARGV[3]) {
    get_map($ARGV[0], $ARGV[1], $ARGV[2], $ARGV[3]);
} elsif ($ARGV[0] eq "--csv") {
    read_csv();
} else {
    print STDERR 'street2wp.pl by Stefan "tommie" Tomanek <stefan@pico.ruhr.de>'."\n";
    print STDERR "Usage:\n";
    print STDERR "    street2wp.pl \"waypoint name\" \"Street <nr>\" City ZIP\n";
    print STDERR "or\n";
    print STDERR "    street2wp.pl --csv\n";
    print STDERR "to read data of the format 'name;street;city;zip' from stdin, with one address in each line.\n"
}


