#!/usr/bin/perl -w
# This program is in the Public Domain.

my $email="";
my $password="";

use strict;
use Tk;
use Tk::Adjuster;
use Tk::HList;
use Tk::ROText;
use Tk::ProgressBar;
use LWP::UserAgent ();

my $main = Tk::MainWindow->new;

my $selector = $main->HList(-columns => 4);
my $display = $main->ROText();

my $selected_venue = 0;
my $selected_row = "";

my $progress = $main->ProgressBar();
my %rowstyles = ();

$selector->pack(-expand => 1, -fill => 'both');
$display->pack(-expand => 1, -fill => 'both');
$progress->pack(-fill => 'both');

my $email_entry;
my $password_entry;
if(!$email or !$password)
{
  $display->insert ('end', "Email\n");
  $email_entry = $display->Entry();
  $display->windowCreate('end', '-window' => $email_entry);
  $display->insert ('end', "\npassword\n");
  $password_entry = $display->Entry(-show => '*');
  $display->windowCreate('end', '-window' => $password_entry);
  $display->insert ('end', "\n");
}

my $web = 0;

sub simplify {
  my $string = shift;
  $string =~ s/&amp;/&/;
  return $string;
}

my $login = sub {
  if(!$email or !$password)
  {
    $email = $email_entry->get;
    $password = $password_entry->get;
  }
  $display->delete ('0.0', 'end');
  $web = LWP::UserAgent->new();
  $web->cookie_jar ( {} );
  $web->post("http://my.meetup.com/reg/signin/",
	     [ email => $email, password => $password ]);
  my $res =
    $web->request(HTTP::Request->new('GET',
				     'http://my.meetup.com/?sortby=date'));
  if ($res->is_error)
  {
    print "error fetching list of meetups\n";
    return;
  }
  my $page = $res->content;
  my @rows = ($page =~ m|<table(.*?)/table|sg);
  my $rownum = 0;
  foreach my $row (@rows)
  {
    my ($url, $name, $date) =
      ($row =~ m|"http://([^./]*)\.meetup\.com/".*?<b>(.*?)</b>.*?
                <td[^>]*>(.*?)< |sgx );
    if (!defined($url) or !defined($name) or !defined($date))
    {
      print "Bad row $rownum\n";
      $rownum++;
      next;
    }

    $name = simplify($name);
    $rowstyles{$url} = $selector->ItemStyle('text');
    $selector->add($url, -at => $rownum, -itemtype=> 'text', -text=> $name,
		   -style => $rowstyles{$url} );
    $selector->itemCreate($url, 1, -itemtype => 'text', -text => $date,
			 -style => $rowstyles{$url} );
    $rownum++;
  }

};

my $submit = sub {
  my $rowurl = 'http://' . $selected_row . '.meetup.com/';
  $web->post( $rowurl, [ venueId => $selected_venue,
			 action => 'vote',
			 op => 'vote' ] );
};

my $switcher = sub {

#  This doesn't work as expected
#  $main->Busy(-recurse => 1);

  $progress->value(20);
  $selected_row = shift;
  $display->delete ('0.0', 'end');
  $display->insert ('end', "$selected_row");

  $display->insert ('end', "\n");

  my $rowurl = 'http://' . $selected_row . '.meetup.com/';

  print "Doing request 1...";
  my $res = $web->request(HTTP::Request->new('GET', $rowurl));
  print "done\n";
  $progress->value(50);

  if ($res->is_error)
  {
    print "error fetching info1 for $selected_row\n";
    return;
  }
  my $page1 = $res->content;
  
  if ($page1 =~ /is cancelled/)
  {
    $display->insert ('end', "Cancelled");
    ($rowstyles{$selected_row})->configure(-background => 'red');
    $progress->value(100);
    return;
  }

  if ($page1 =~ /RSVP counts./) #it's in RSVP stage
  {
    $display->insert ('end', "Location is\n");
    my ($location) =
      ($page1 =~ m|<strong>([^<]*)$|m);
    $display->insert ('end', $location);
    $display->insert ('end', "\n");
    my ($url2) = ($page1 =~ /href="([^>]+?)"[^>]+><b>See Voting and RSVP/);
    $url2 = $rowurl . $url2;
    $res = $web->request(HTTP::Request->new('GET', $url2));
    my $page2 = $res->content;
    my @rows = ($page2 =~ m|<tr>.*?</tr>|gs);
    print "number of rows is ", scalar(@rows), "\n";
    my $rsvp = 0;
    foreach my $row (@rows)
    {
      if (my ($num) = ($row =~ m|<td.*<td.*<td.*?(\d+)|s))
      {
	$rsvp = $rsvp + $num;
      }
    }
    $display->insert ('end', "$rsvp RSVPs\n");
    $progress->value(100);
    return;
  }

# Build venue-name/venueId hash table
  $selected_venue = 0;
  my @rows = ($res->content =~ m|<tr>(.*?formVotelabel.*?)</tr>|sg);

  my %venuehash = ();
  my @venuestodo = ();

  foreach my $row (@rows)
  {
    my ($vid, $vname) =
      ($row =~ m|value="(.*?)".*?"formVotelabel"\W*(.*?)\s*?<|s );
    
    if (!grep (/^$vid$/ , values(%venuehash)) )
    {
      $venuehash{$vname} = $vid;
      push (@venuestodo, $vname);
    }
    if ($row =~ /checked/)
    {
      $selected_venue = $vid;
    }
  }
  
  $progress->value(50);
  $main->idletasks();

  my @places =
    ($page1 =~ 
     /<input type="radio"[^<]*value="([^<]*?)".*?<span[^>]*>([^<]*)/sg );

  my ($url2) = ($page1 =~ /href="([^"]+)"[^>]+>see tally/); #"
  $url2 = $rowurl . $url2;

  $res = $web->request(HTTP::Request->new('GET', $url2));

  @rows = ($res->content =~ m|<tr>(.*?<div>.*?)</tr>|sg);

  foreach my $row (@rows)
  {
    my ($vname, $votes) =
      ($row =~ m|"venueName">([^<]*).*<b>\s*?(\S.*?)\s*?<|s );
    $vname = simplify($vname);
    
    $votes = $votes + 0 ;
    if (!defined($vname))
    {
      print "  vname is undefined at line 151\n";
    }
    my $vid = $venuehash{$vname};
    $vid = -1 if (!defined($vid));
    @venuestodo = grep {lc($_) ne lc($vname) } @venuestodo;

    my $rb = $display->Radiobutton(-variable => \$selected_venue,
				   -value => $vid);
    $display->windowCreate('end', '-window' => $rb);
    $display->insert ('end', "$votes $vname\n");
  }

  foreach my $vname (@venuestodo)
  {
    my $rb = $display->Radiobutton(-variable => \$selected_venue,
				   -value => $venuehash{$vname});
    $display->windowCreate('end', '-window' => $rb);
    $display->insert ('end', "0 $vname\n");
  }

  my $submit_button = $display->Button(-text => 'Submit Vote',
				       -command => $submit);
  $display->windowCreate('end', '-window' => $submit_button);
  $progress->value(100);
  $main->Unbusy(-recurse => 1);

};

my $login_button = $display->Button(-text => 'Login', 
				    -command => $login);
$display->windowCreate('end', '-window' => $login_button);

$selector->configure(-command => $switcher);
MainLoop;

