#!/usr/bin/perl
###########################################
# vrunner - Virtual Runner for .yaml files
# Mike Schilli, 2013 (m@perlmeister.com)
###########################################
use strict;
use warnings;
use Imager;
use Imager::Plot;
use YAML qw( LoadFile );

my $plot = Imager::Plot->new(
  Width  => 600,
  Height => 400,
  GlobalFont => '/usr/share/fonts/' .
   'truetype/freefont/FreeSans.ttf');

my( $first, $second ) = @ARGV;
die "usage: $0 1.yaml 2.yaml" if
  !defined $second;

my @first_pairs = data_extract( $first );
my @second_pairs = data_extract( $second );

data_set_add( 
    $plot, \@first_pairs, "green" );
data_set_add( 
    $plot, \@second_pairs, "red" );

my $img = Imager->new(xsize => 650,
                      ysize => 450);

$img->box(filled => 1, color => 'white');

    # Add text
$plot->{'Ylabel'} = 'Distance';
$plot->{'Xlabel'} = 'Time';
$plot->{'Title'}  = 'Fast Pace vs. Slow';

$plot->Render(Image => $img,
    Xoff => 40, Yoff => 420);

$img->write(file => "vrunner.png");

###########################################
sub data_extract {
###########################################
  my( $file ) = @_;

  my $base;
  my @pairs = ();

  my $data = LoadFile( $file );
  for my $record ( @$data ) {
    my $time = $record->{ timestamp };
    my $dist = $record->{ distance };
    $base = $time if !defined $base;
    $dist =~ s/\D+$//;
    push @pairs, [ $time - $base, $dist ];
  }

  return @pairs;
}

###########################################
sub data_set_add {
###########################################
  my( $plot, $data, $color ) = @_;

  $plot->AddDataSet( 
    X => [ map { $_->[ 0 ] } @$data ],
    Y => [ map { $_->[ 1 ] } @$data ],
    style => {
      marker => {
        size => 2,
        symbol => "circle",
        color  => 
          Imager::Color->new($color),
      }
    }
  );
}
