#!/usr/bin/perl
# Copyright (c) 2008 - Dave Hansen <dave@sr71.net>
use strict;
use LWP::UserAgent;
use daveperl;

STDOUT->autoflush(1);

my $home = $ENV{HOME};
my $username = cat_file($home."/.picasa-user");
my $password = cat_file($home."/.picasa-password");
chomp $username;
chomp $password;
my $cache_dir = $home.'/.picasa-download/';

use Net::Google::PicasaWeb;

my $user = Net::Google::PicasaWeb::User->new( $username,
{ password => $password }
);
my @albums = $user->get_albums();
printf "albums: %d\n", (scalar @albums);
my %pic_urls;
foreach my $album (@albums) {
	printf "album title: '%s'\n", $album->title;
	my @photos = $album->get_photos();
	my $ua;
	foreach my $pic (@photos) {
		my $title = $pic->title;
		$title =~ tr/A-Z/a-z/;
		printf "\tpic: '%s' ", $title;
		#rintf "content: '%s'\n", $pic->content;
		for my $link ($pic->entry->links) {
			my $type = $link->type;
			next if $type ne 'image/jpeg';
			$pic_urls{$title} = $link->href;
			print "got url...";
			last;
		}
		print "\n";
		#printf "keys: ->%s<-\n", join(',', $pic->foo);
	}
}
mkdir_p $cache_dir;
foreach my $pic (keys %pic_urls) {
	if (-e $cache_dir.$pic) {
		#rint "$pic already downloaded\n";
		delete $pic_urls{$pic};
		next;
	}
}
if (!scalar(keys %pic_urls)) {
	printf("up to date, no downloads necessary (%d)\n", scalar(keys %pic_urls));
	exit(0);
}
printf "locating existing files...";
my @allfiles = findfiles($home."/pictures");
printf "done\n";
my %picfiles;
foreach my $pic (@allfiles) {
	next if $pic !~ /\.jpg$/i;
	next if $pic =~ '/tn/';
	$picfiles{basename($pic)} = 1;
}
my @copied_pics;
my $dest_dir = $home."/pictures/new";
foreach my $pic (sort keys %pic_urls) {
	if (defined $picfiles{$pic}) {
		cat_into_file(`date`, $cache_dir.$pic);
		printf("$pic already in album\n");
		next;
	}
	my $url = $pic_urls{$pic};
	printf "getting $pic from picasa...", $url;
	my $ua = $user->_get_ua;
	my $res = $ua->get($url);
	printf " success: %s len: %d\n", $res->is_success, length($res->content);
	next if !$res->is_success;
	push @copied_pics, $pic;
	cat_into_file($res->content, $pic);
	system('exifautotran', $pic);
	mv_file($pic, $dest_dir);
}
if (scalar @copied_pics) {
	chdir $dest_dir || die "unable to cd $dest_dir";
	system("sort-run-album", @copied_pics);
}
