#!/usr/bin/perl -w
use strict;
use CGI;
use SOAP::Lite;
use SVG;
my $cgi = new CGI;
my $query = $cgi->param('q');
my $part = $cgi->param('p');

if (!defined($query) || $query eq "") {
  print <<EOF;
content-type: text/html

<html><head><title>Google SVG Search</title></head>
<body><h1>Google SVG Search</h1>
<form><input type=text name=q><input type=submit value='Google Search'></form>
</body></html>
EOF
}
else {
  if (!defined($part) || $part eq "") {
    print <<EOF;
content-type: text/html

<html><head><title>Search Results</title></head>
<body><h1>Search Results</h1>
<embed src="?q=$query&p=svg" name="results" width="600" height="600"
type="image/svg+xml" pluginspage="http://www.adobe.com/svg/viewer/install/">
</embed></body></html>
EOF
  }
  else {
    my $googleSearch = SOAP::Lite->service('file:GoogleSearch.wsdl');
    my $key = 'TfUiMIhnd3fXP/ZLLbMmSws0Q2wjGYWp';
    $ENV{HTTP_proxy} = 'http://proxy.puma-ag.lan:3128';
    my $result = $googleSearch->doGoogleSearch($key, $query, 0, 10, 'false', '', 'false', '', 'latin1', 'latin1');
    
    my $i = 0;
    my $svg = new SVG;
    foreach my $e (@{$result->{'resultElements'}}) {
      svgelement($i, $svg, $e->{'summary'}, $e->{'title'}, $e->{'URL'}, $e->{'directoryCategory'}->{'fullViewableName'}, $e->{'directoryTitle'}, $e->{'snippet'});
      $i++;
      #  foreach my $key (keys(%$e)) {
      #    print $key, ': ', $e->{$key}, "\n";
      #  }
    }
    print "content-type: image/svg+xml\n\n";
    print $svg->render();
  }
}

sub svgelement {
  my ($i, $svg, $summary, $title, $url, $dirname, $dirtitle, $dirsnippet) = @_;
  if ($i > 8) { return; }
  my @pos = ([1,1],[1,0],[2,0],[2,1],[2,2],[1,2],[0,2],[0,1],[0,0]);
  my $w = 200;
  my $h = 150;
  $svg->rect(x=>$w*$pos[$i][0], y=>$h*$pos[$i][1], width=>$w, height=>$h, stroke=>'black', fill=>'white');
  my $tag = $svg->anchor(-href=>$url);
  addtext($tag, stripHTML($title), 12, $w*$pos[$i][0], $h*$pos[$i][1]);
  addtext($tag, stripHTML($dirsnippet), 60, $w*$pos[$i][0], $h*$pos[$i][1]);
}

sub stripHTML {
  my ($str) = @_;
  $str=~s/<.*?>//sg;
  return $str;
}

sub addtext {
  my ($tag, $str, $y, $w, $h) = @_;
  my @words = split(/ /, $str);
  my $line = '';
  my $row = 1;
  foreach my $word (@words) {
    if (length($line) + length($word) > 30) {
      $tag->text(x=>$w+2, y=>$h+$y+12*$row)->cdata($line);
      $row++;
      $line = '';
    }
    $line .= $word . ' ';
  }
  $tag->text(x=>$w+2, y=>$h+$y+12*$row)->cdata($line);
}

sub addline {
  my ($tag, $line, $y, $w, $h) = @_;
}
