#!perl
# compare dot-generated images with graphs drawn by Tk::GraphViz

use strict;
use warnings;
use File::Temp qw(tempfile);
use Tk;
use Tk::Pane;
use Tk::GraphViz;

# Get files from the command line, if supplied

my @dots = @ARGV ? @ARGV : glob "t/graphs/directed/*";
my $async = 1;

my $mw = MainWindow->new();

# Frame for the two images
my $topFrame = $mw->Frame->pack(-side => 'top', -fill => 'both', -expand => 1);

# left image, including a label
my $imageLabel = makeScrolledWidget(
  $topFrame, 'left', "Dot-Generated GIF Image", 'packAdjust',
  Pane => -sticky => 'nsew',
)->Label->pack(-fill => 'both', -expand => 1);

# right image, including a label
# Right picture is a Tk::GraphViz object
my $gv = makeScrolledWidget(
  $topFrame, 'left', 'Tk::GraphViz-Generated Canvas', 'pack',
  GraphViz => -background => 'white',
)->createBindings;

my $buttonFrame = $mw->Frame->pack(-side => 'bottom');
my $statusLabel = $mw->Label->pack(-side => 'bottom');
my $nextButton = $buttonFrame->Button(-command => \&showDots, qw(-text Next -underline 0 -state disabled))->pack(-side => 'left');
$buttonFrame->Button(-command => [$mw, 'destroy'], qw(-text Quit -underline 0))->pack(-side => 'right');
$mw->bind('<Key-n>' => \&showDots);
$mw->bind('<Key-q>' => [$mw, 'destroy']);

$mw->geometry("800x400");
showDots();

MainLoop;

sub makeScrolledWidget {
  my ($top, $side, $label, $pack, @scrolled) = @_;
  my $frame = $top->Frame(-relief => 'sunken')
    ->$pack(-fill => 'both', -expand => 1, -side => $side);
  $frame->Label(-text => $label)->pack(-side => 'top');
  $frame->Scrolled(@scrolled, -scrollbars => 'osoe')
    ->pack(-fill => 'both', -expand => 1,  -side => 'top');
}

sub showDots {
  return if !@dots;
  my $currentFile = shift @dots;
  $statusLabel->configure(-text => "Generating GIF for $currentFile ...");
  $mw->Busy;
  $mw->update;
  $imageLabel->configure(-image => GenerateImage($imageLabel, $currentFile));
  $statusLabel->configure(-text => "Generating Tk::GraphViz Canvas for $currentFile ...");
  $mw->update;
  $gv->show($currentFile, async => $async);
  $statusLabel->configure(-text => $currentFile);
  $mw->Unbusy;
  $nextButton->configure(-state => @dots ? 'normal' : 'disabled');
}

##############################################
# Sub to generate gif file from dot file
sub GenerateImage {
  my ($frame, $filename) = @_;
  die "Can't find file '$filename'\n" unless -f $filename;
  print "Processing file $filename\n";
  my (undef, $tempfile) = tempfile('XXXX', TMPDIR => 1, UNLINK => 1);
  my @command = (qw(dot -Tgif), $filename, qq{-o$tempfile});
  system @command and die "Error executing @command\n".$!;
  my $image = $frame->Photo(-file => $tempfile);
  return $image;
}
