#!/usr/bin/perl

use FileHandle;
use Image::Magick;
use Flickr::API;
use XML::Parser::Lite::Tree::XPath;
use Getopt::Std;

getopt('d');

$apikey = 'YOUR-API-KEY';
$apisecret = 'YOUR-API-SECRET';

$groupNSID = '81474450@N00';  # Utata group NSID
$filename = 'badge';          # The output file name
$mapname = 'badge-map';       # The name given to the image map

$dir = './';
$dir = $opt_d if (defined($opt_d));

if ($dir !~ /\/$/)
{
    $dir .= '/';
}


$flickr = new Flickr::API(
  {
    'key'    => $apikey,
    'secret' => $apisecret,
  }); 

$photosCount = 8;

@recentPoolPhotos = ();
$recentPoolPhotosImage = undef;

buildBadge();

# Subroutines start here
sub getRecentPoolPhotos
{
  if ($#recentPoolPhotos == -1)
  {
    my $response = $flickr->execute_method('flickr.groups.pools.getPhotos', 
      {
        'group_id' => $groupNSID,
        'per_page' => $photosCount,
        'page' => 1,
      });

    my $xpath = new XML::Parser::Lite::Tree::XPath($response->{'tree'});

    @recentPoolPhotos = $xpath->select_nodes('/photos/photo');
  }

  @photos = ();
  for ($i = 0; $i < $photosCount; $i++)
  {
    my $p = $recentPoolPhotos[$i];
    push(@photos, $p);
  }

  return @photos;
}

sub getGroupURL
{
  my $response = $flickr->execute_method('flickr.urls.getGroup', 
    {
      'group_id' => $groupNSID,
    });

  my $xpath = new XML::Parser::Lite::Tree::XPath($response->{'tree'});

  my @groups = $xpath->select_nodes('/group');

  return $groups[0]->{'attributes'}->{'url'};
}


sub getGroupIconURL
{
  my $url = "";

  my $response = $flickr->execute_method('flickr.groups.getInfo', 
    {
      'group_id' => $groupNSID,
    });

  my $xpath = new XML::Parser::Lite::Tree::XPath($response->{'tree'});

  my @groups = $xpath->select_nodes('/group');

  if ($#groups >= 0)
  { 
    my $iconServer = $groups[0]->{'attributes'}->{'iconserver'};
    $url = "http://static.flickr.com/$iconServer/buddyicons/$groupNSID.jpg";
  }
  return $url;
}

sub getPhotoPage
{
  my ($p) = @_;
  my $url = 'http://www.flickr.com/photos/' . $p->{'attributes'}->{'owner'} . '/' 
    . $p->{'attributes'}->{'id'} . '/';
}

sub getRecentPoolPhotosAsImage
{
  if (!defined($recentPoolPhotosImage))
  {
    @photos = getRecentPoolPhotos($photosCount);
    $recentPoolPhotosImage = Image::Magick->new;

    for $p (@photos)
    {
      my $img = 'http://static.flickr.com/' . $p->{'attributes'}->{'server'} . '/' 
        . $p->{'attributes'}->{'id'} . '_' . $p->{'attributes'}->{'secret'} 
        . '_s.jpg';
      $recentPoolPhotosImage->Read($img);
    }
  }

  return $recentPoolPhotosImage;
}


sub generateHTML
{
  my ($mapRef) = @_;

  my $s = "<img src=\"$filename.jpg\" width=\"225\" height=\"225\" 
usemap=\"#$mapname\" border=\"0\" />\n";

  $s .= "<map name=\"$mapname\">\n";
  for $item (@$mapRef)
  {
    my $topleftx = $$item[0];
    my $toplefty = $$item[1];
    my $bottomrightx = $topleftx + $$item[2];
    my $bottomrighty = $toplefty + $$item[3];
    my $url = $$item[4];

    $s .= "<area shape=\"rect\" coords=\"$topleftx,$toplefty 
$bottomrightx,$bottomrighty\" href=\"$url\" />\n";
  }
  $s .= "</map>\n";

  my $fh = new FileHandle "> $filename.html";
  if (defined $fh)
  {
    print $fh $s;
    $fh->close;
  }
}

sub addImage
{
  my ($image, $photo, $x, $y, $width, $height, $mapRef, $url) = @_;

  $image->Composite(image => $photo, compose => 'Copy', x => $x, y => $y);
  addMap($mapRef, $x, $y, $width, $height, $url);
}

sub addMap
{
  my ($mapRef, $x, $y, $w, $h, $url) = @_;
  my @location = ($x, $y, $w, $h, $url);
  push (@$mapRef, \@location);
}

sub buildBadge
{
  my @photoDetails = getRecentPoolPhotos();
  my $photos = getRecentPoolPhotosAsImage();
  my @map = ();
  my $mapRef = \@map; 

  my $groupIconImage = Image::Magick->new;
  $groupIconImage->Read(getGroupIconURL());

  $image = Image::Magick->new;
  $image->Set(size=>'225x225');
  $image->ReadImage('xc:white');

  addImage($image, $photos->[0], 0, 0, 75, 75, $mapRef,   
     getPhotoPage($photoDetails[0]));
  addImage($image, $photos->[1], 75, 0, 75, 75, $mapRef, 
     getPhotoPage($photoDetails[1]));
  addImage($image, $photos->[2], 150, 0, 75, 75, $mapRef, 
     getPhotoPage($photoDetails[2]));
  addImage($image, $photos->[3], 0, 75, 75, 75, $mapRef, 
     getPhotoPage($photoDetails[3]));
  addImage($image, $photos->[4], 150, 75, 75, 75, $mapRef, 
     getPhotoPage($photoDetails[4]));
  addImage($image, $photos->[5], 0, 150, 75, 75, $mapRef,  
     getPhotoPage($photoDetails[5]));
  addImage($image, $photos->[6], 75, 150, 75, 75, $mapRef, 
     getPhotoPage($photoDetails[6]));
  addImage($image, $photos->[7], 150, 150, 75, 75, $mapRef, 
     getPhotoPage($photoDetails[7]));
  addImage($image, $groupIconImage->[0], 88, 88, 48, 48, $mapRef, getGroupURL());


  $image->Write(filename => $dir . $filename . '.jpg', quality => 85);

  undef $image;

  generateHTML($mapRef);
}
