#!/usr/bin/perl -w

$WAITENTER=1;

use v5.10;
use WWW::Mechanize::Firefox;

$ENV{'SHELL'}='/bin/bash';


# get credentials for site from file named ./.creds-pcplus
open(CREDS,'<.creds-pcplus') or die;
$/=undef;
$_=<CREDS>;
close(CREDS);
($user)=/^user=(.*)/mi or die;
($pass)=/^pass=(.*)/mi or die;
$/="\n";



$www=WWW::Mechanize::Firefox->new(
  agent		=>'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)',
  autodie	=>0,
  timeout	=>120,
  tab		=>qr/MUUG Home|PC Plus/,
  bufsize	=>5000000
);
$www->repl->repl->client->{telnet}->timeout(60); # telnet timeout workaround



$www->get('https://www.pcplus.ca/');


# check it we're logged in yet, and skip login if we are
$con=$www->content;
if ($con!~/>Sign Out</) {


  &Wait('click sign in button to show form');

  $www->click({'xpath'=>'//a[@href="#signinForm"]',synchronize=>0});
  # no synchronize here, as dynamic-popup js clicks don't trigger the correct dom events
  sleep 1;


  &Wait('enter sign in credentials');

  $www->field('/t4g/loyalty/userprofile/LoyaltyLoginFormHandler.value.loyaltyEmail',$user);
  $www->field('/t4g/loyalty/userprofile/LoyaltyLoginFormHandler.value.password'    ,$pass);


  &Wait('click sign in');

  $www->click({'xpath'=>'//button[@name="loginButton"]',synchronize=>1});

}


say "the current URI is ".$www->uri."\n";


&Wait('click offers');

$www->click({'xpath'=>'//a[text()="OFFERS"]','synchronize'=>1});


&Wait('click close load-all popup (if present)');

$www->click({'xpath'=>'//div[@id="cboxClose"]','synchronize'=>0});
sleep 2;


#&Wait('click load-all-offers');

#$www->click({'xpath'=>'//button[text()="Load All Offers"]','synchronize'=>1});


# let's scrape the images

$i=0;
$con=$www->content;

while ($con=~/ "offerThumb">  \s*  <img\s+src="([^"]+)"  .*?  "offerPoints">\s*([0-9,]+)  /sigx) {
  ($url,$pts)=($1,$2);
  $pts=~tr/,//d;

  $saveto=sprintf('pcplus%02d.jpg',$i++);

  &Wait("download image to $saveto from $url");

  &DownloadFile($url,$saveto);

  push(@offers,[$saveto,$pts]);

}


# piece de resistance, tying into to a previous month's netpbm presentation
&Wait('make a nice collage');

foreach $offer (@offers) {

  ($file,$pts)=@$offer;

  system "jpegtopnm $file 2>/dev/null | ppmlabel -color black -x 5 -size 19 -text '$pts' > $file.pcplustmp";

}


system "pnmcat -lr *.pcplustmp | pnmtojpeg > collage.jpg";

system "rm *.pcplustmp";

exit;


sub Wait {
  my($m)=shift;
  say "about to $m".($WAITENTER?' [ENTER]':'');
  sleep(rand(3)+1),return if !$WAITENTER;
  <STDIN>;
}


sub DownloadFile {
  my $url =shift;
  my $file=shift;

  my $progress=$www->save_url( $url => $file );
  my $progressstate;
  my $i;
  while (1) {
    $progressstate=$progress->{currentState};
    last if $progressstate==3;
    sleep 1;
  }
  die if !$www->success();
}


__END__
