#!/usr/bin/perl
use LWP::UserAgent;
use URI::URL;
use Image::Magick;

my $ua = LWP::UserAgent->new;
$ua->timeout(10);
$ua->env_proxy;
$ua->agent("Opera/9.80 (X11\; Linux x86_64\; U\; en) Presto/2.9.168 Version/11.50");
my @ns_headers = (
   'Accept' => 'image/gif, image/x-xbitmap, image/jpeg, 
        image/pjpeg, image/png, */*',
   'Accept-Charset' => 'iso-8859-1,*,utf-8',
   'Accept-Language' => 'en-US',
);

my $spacedirpath = 'home/superkuh/www/spaceweather';
my $useragent = "--user-agent=\"Opera/9.80 (X11\; Linux x86_64\; U\; en) Presto/2.9.168 Version/11.50\"";
my $ARmovieHTML = '/home/superkuh/www/spaceweather/AR.html';
my $logpathandfile = '/home/superkuh/tests/ARlogs.txt';

`wget $useragent \"http://www.lmsal.com/forecast/lastmagnetograma.jpg\" --output-document=/$spacedirpath/numberedAR.jpg`;


# http://www.lmsal.com/forecast/AR/

my @activeregions;
@activeregions = gatheractiveregions("http://www.lmsal.com/forecast/AR/");
print scalar(@activeregions) . " active regions found.\n";

logging(@activeregions);

print "Generating AR movies... \n";
open (ARHTML, ">$ARmovieHTML") or die "can't make $ARmovieHTML.\n$!";
print ARHTML "<H3>Generated by <a href=\"http://www.lmsal.com\">LMSAL</a>, <a href=\"http://www.lmsal.com/forecast/ARmovies.html\">4-d AR movies</a>\n";
print ARHTML "<br /><img src=\"numberedAR.jpg\" /><br />";
foreach my $region (@activeregions) {
	print ARHTML "<img src=\"$region.gif\" />\n";
	if (-d "/$spacedirpath/AR/$region") {
		print "dir for $region exists.\n";
		movie("http://www.lmsal.com/forecast/AR/",$region,"/$spacedirpath/AR/$region/","$region.gif");
	} else {
		mkdir "/$spacedirpath/AR/$region";
		print "Created dir $spacedirpath/AR/$region/ for temp.\n";
		movie("http://www.lmsal.com/forecast/AR/",$region,"/$spacedirpath/AR/$region/","$region.gif");
	}
}
close ARHTML;

sub gatheractiveregions {
	my ($url) = @_;
	my @regions;
	print "Gathering regions...";
	my $response = $ua->get("$url", @ns_headers);
	if ($response->is_success) {
		my $html = $response->decoded_content;
		my @htmluh = split(/\n/, $html);
		foreach my $line (@htmluh) {
			# <td><a href="1289/">
			# <td><a href="1290/">1290/</a>
			if ($line =~ m#<a href=\"(\d+)\/#) {
				my $ARnum = $1;			
				push(@regions, $ARnum);
			}
		}	
	}
	return @regions;
}

sub makekeyfor {
	my $filepath = shift;
	# /home/superkuh/www/spaceweather/AR/1289/d2f000_20110917_053650.gif
	# keyname: home/superkuh/www/spaceweather/AR/1289//d2f000_20110917_053650.gif
	$filepath =~ m#\d{4}/(.+\.gif)$#;
	$name = $1;
	#print "keyname: $name\n";
	return $name;
}

sub movie {
	my ($url,$region,$tempdir,$outname) = @_;
	my @images;
	my @existingimages;
	my %imagecheck;

	print "Gathering images for AR$region to output $outname...\n";
	@existingimages = <$tempdir*.gif>;
	%imagecheck = map { makekeyfor($_) => 1 } @existingimages;
	print "keys: " . scalar(keys %imagecheck) . "\n";

	my $response = $ua->get("$url$region/", @ns_headers);
	if ($response->is_success) {
		my $html = $response->decoded_content;
		my @htmluh = split(/\n/, $html);
		foreach my $line (@htmluh) {
			# <a href="d2f000_20110917_053650.gif">
			# <a href=\"(d2f\d{3}_\d{8}_\d+\.gif)">
			if ($line =~ m#<a href=\"(d2f\d{3}_\d{8}_\d+\.gif)">#) {
				my $image = $1;			
				push(@images, "$image");
				#print scalar(@images) . ": $url$image\n";	
			}
		}

		if (@images) {
			foreach my $image (@images) {
				#print "imgname: $image, ";
				if ($imagecheck{$image}) {
					#print "exists, skipping $image.\n";
				} else {
					$ua->default_header('Referer' => "$url$region/HMI.html");
 					my $response = $ua->get("$url$region/$image", @ns_headers);
					my $result = $response->status_line;
					my $content = $response->content();
					print ("$url$region/$image - $result\n");
					if ($result =~ /200/) {
						open (FILE, ">/$tempdir/$image") or warn "Could not open output!: $!";
						binmode (FILE);
						print FILE $content;
						close FILE;
					} else { warn "unable to grab file \$url\$region/\$image: $url$region/$image\n"; }
				}
			}

			makeGIF($outname,$tempdir,@images);

		} else { warn "nothing in \@images"; }
		
	} else { warn "can't get the url: $url to load\n"; }	
}

sub makeGIF {
	my ($outname, $tempdir, @images) = @_;
	print "Making animated GIF\nout: /$spacedirpath/$outname, tempdir: $tempdir, images: " . scalar(@images) . "\n"; 
	my $hundredths_of_second = 10;
	my ($anigif);
	$anigif = new Image::Magick;
	foreach my $image (@images) {
		#print "/$tempdir/$image\n";
		$anigif->Read("/$tempdir/$image");
	}
	$anigif->Write(delay => $hundredths_of_second, loop => 0, filename => "/$spacedirpath/$outname");
}

sub logging {
	my @regions = @_;
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
	$year += 1900;
	open (LOG, ">>$logpathandfile") or die "can't make $logpathandfile.\n$!";
	print LOG "$year-$mon-$mday @ $hour:$min _ ";
	foreach my $region (@regions) {
		print LOG "$region,";
	}
	print LOG "\n";
	close LOG;
}
