#!/usr/bin/perl
#
# FreeBSD Events List Publishing to Yahoo! Upcoming Service.
#
# Copyright(c) 2008 Murray Stokely <murray@FreeBSD.org>
# June 8, 2008
#

use WebService::Upcoming;

my $upco = new WebService::Upcoming("XXENTERHERE");

sub printEvent {
    my %eventhash = @_;
    foreach my $key (keys %eventhash) {
	printf "%s: %s\n", $key, $eventhash{$key};
    }
}

sub findMetro(%) {
    my %params = @_;
    my $objc = $upco->call("metro.search", \%params);
    die("ERROR: ".$upco->err_text()."\n") if (!defined($objc));
    my $max_id = -1;
    my $max_score = -1;
    foreach (@{$objc})
    {
	$tempscore = scoreMatch($params{search_text}, $_->name());
	if ($tempscore > $max_score) {
	    $max_score = $tempscore;
	    $max_id = $_->id();
	    $max_name = $_->name();
	    if ($tempscore eq $GLOBAL_MAX_SCORE) {
		return $max_id;
	    }
	}
    }
    printf "Top metro result: %s %s %s\n", $max_name, $max_id, $max_score;
    return $max_id;
}

sub getMetro($$$) {
    my ($city, $country, $country_id) = @_;
#    printf "Finding metro for %s city (%s country) (country_code = %s)\n", $city, $country, $country_id;
    my %params;
    $params{search_text} = $city;
    $params{country_id} = $country_id;
    my $id = findMetro(%params);
    return $id if $id > 0;
    delete($params{country_id});
    $params{search_text} = "$city $country";
    $id = findMetro(%params);
    return $id if $id > 0;
    $params{search_text} = $city;
    $id = findMetro(%params);
    return $id;
}

sub getCountry($$) {
    my ($countrycode, $country) = @_;
    printf "Getting country list for %s (%s)\n", $country, $countrycode;
    my $objc = $upco->call("metro.getCountryList");
    die("ERROR: ".$upco->err_text()."\n") if (!defined($objc));
    my %matches;
    foreach (@{$objc})
    {
	$matches{$_->id()} = 0;
	$code = $_->code();
	$name = $_->name();
	if ($countrycode =~ /^$code$/i) {
	    return $_->id();
	}
#	    $matches{$_->id()} += 2;
#	    printf "countrycode match : %s, %s, %s\n", $_->name(), $_->code(), $_->id();
#	} elsif ($countrycode =~ /^$code/i) {
#	    $matches{$_->id()} += 1;
#	    printf "countrycode partial match : %s, %s, %s\n", $_->name(), $_->code(), $_->id();
#	}
#	if ($country =~ /^$name$/i) {
#	    $matches{$_->id()} += 2;
#	    printf "countryname match : %s, %s, %s\n", $_->name(), $_->code(), $_->id();
#	} elsif ($country =~ /^$name/i) {
#	    $matches{$_->id()} += 1;
#	    printf "countryname partial match : %s, %s, %s\n", $_->name(), $_->code(), $_->id();
#	}
    }
    return -1;
}

my $GLOBAL_MAX_SCORE = 6;

sub scoreMatch($$) {
    my ($two, $one) = @_;
    if ($one =~ /^$two$/) {
	return 6;
    } elsif ($one =~ /^$two$/i) {
	return 5;
    } elsif ($one =~ /^$two/) {
	return 4;
    } elsif ($one =~ /^$two/i) {
	return 3;
    } elsif ($one =~ /$two/) {
	return 2;
    } elsif ($one =~ /$two/i) {
	return 1;
    }
    return 0;
}

sub findVenue(%) {
    my %params = @_;
    my $objc = $upco->call("venue.search", \%params);
    die("ERROR: ".$upco->err_text()."\n") if (!defined($objc));
    if ($#{$objc} >= 0) {
	my $max_id = -1;
	my $max_score = -1;
	foreach (@{$objc})
	{
	    $tempscore = scoreMatch($params{search_text}, $_->name());
	    if ($tempscore > $max_score) {
		$max_score = $tempscore;
		$max_id = $_->id();
		$max_name = $_->name();
		if ($tempscore eq $GLOBAL_MAX_SCORE) {
		    return $max_id;
		}
	    }
#	    print("VENUE: ".$_->name()." ID: ".$_->id()." SCORE: ".$tempscore."\n");
	}
	printf "Top result: %s %s %s\n", $max_name, $max_id, $max_score;
	return $max_id;
    }
    return -1;
}

sub getVenue(%) {
    my %event = @_;
    my $country_id = getCountry($event{'LOCATION-COUNTRY-CODE'}, $event{'LOCATION-COUNTRY'});
    my $metro_id = getMetro($event{'LOCATION-CITY'}, $event{'LOCATION-COUNTRY'}, $country_id);
    my %params;
    $params{search_text} = $event{'LOCATION-SITE'};
    $params{country_id} = $country_id if $country_id > 0;
    $params{metro_id} = $metro_id if $metro_id > 0;
    my $id = findVenue(%params);
    return $id if $id > 0;
    delete($params{metro_id});
    $id = findVenue(%params);
    return $id;
}

sub addEvent(%) {
    my %event = @_;
    printf "In addEvent for %s (%s)\n", $event{'NAME'}, $event{'LOCATION-COUNTRY-CODE'};
    my $venue_id = getVenue(%event);
    unless ($venue_id > 0) {
	printf "Can not find venue, skipping this event.\n";
	return;
    }

    $mytoken = "getyourown";
    printf "NAME: %s\nVENUE_ID: %s\nCATEGORY_ID: %s\nSTART_DATE: %s\nend_date: %s\ndescription: %s\nurl: %s\n", $event{NAME}, $venue_id, 5, $event{"STARTDATE"}, $event{"ENDDATE"}, $event{"DESC"}, $event{"URL"};

    my $objc = $upco->call("event.add", {
	"token" => $mytoken,
	"name" => $event{NAME},
	"venue_id" => $venue_id,
	"category_id" => 5,
	"start_date" => $event{STARTDATE},
	"end_date" => $event{ENDDATE},
	"description" => $event{DESC},
	"url" => $event{URL}});
    die("ERROR: ".$upco->err_text()."\n") if (!defined($objc));
    printf "ADD RESULTS - %s\n\n", $#{$objc};
#    foreach (@{$objc})
#    {
#	print "Line of output!?\n"
#	$tempscore = scoreMatch($params{search_text}, $_->name());
#    }
    # Need token.
    # name --> event{NAME}
    # venue_id -> (numeric, TBD)
    # category_id -> (numeric -- educational)
    # start_date -> event{START_DATE}
    # end_date -> event{END_DATE}
    # description -> event{DESC}
    # url -> event{URL}
    #
}

open(EVENTS_FILE, "upcoming_events.txt") || die "Could not open upcoming_events.txt : $!";

my $in_event = 0;
my $in_desc = 0;
my $eventdict = {};
my @events;
foreach my $line (<EVENTS_FILE>) {
    chomp $line;
    if ($line =~ /^EVENT:/) {
	$in_event = 1;
	if ($in_desc eq 1) {
	    # print
	    push(@events, $eventdict);
	    $in_desc = 0;
	}
	$eventdict = {};
	next;
    }
    next unless $in_event;
    if ($line =~ /^([A-Z-_]+)\: (.*)$/) {
	$eventdict->{$1} = $2;
	if ($1 eq 'DESC') {
	    $in_desc = 1;
#	    printf "in_desc! eventdict{%s} = %s\n", $1, $2;

	}
#	print "Matched $1 -> $2\n";
	next;
    }
    if ($in_desc) {
	$eventdict->{DESC} .= $line;
    }
#    print "In event: $line\n";
}
if ($in_desc eq 1) {
    push(@events, $eventdict);
    $in_desc = 0;
}

printf "Number of events: %s\n", $#events + 1;

my %event = ();
foreach my $eventref (@events) {
    %event = %$eventref;

    my $objc = $upco->call("event.search",
			   {
			       "search_text" => $event{NAME}
			   });
    die("ERROR: ".$upco->err_text()."\n") if (!defined($objc));
    if ($#{$objc} >= 0) {
	printf "%s already exists on upcoming.yahoo.com, skipping.\n", $event{NAME};
	next;
    }
    addEvent(%event)
#    printf "RESULTS - %s\n\n", $#{$objc};
#    foreach (@{$objc})
#    {
#	print("EVENT: ".$_->name()." on ".$_->start_date()."\n");
#    }

}

die "DONE TESTING MURRAY";

die("ERROR: ".$upco->err_text()."\n") if (!defined($objc));
foreach (@{$objc})
{
    print("EVENT: ".$_->name()." on ".$_->start_date()."\n");
}
