#!/usr/bin/perl -w
# -*- perl -*-

#
# Author: Slaven Rezic
#
# Copyright (C) 2006,2007,2009,2011,2012,2015,2016 Slaven Rezic. All rights reserved.
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
# Mail: slaven@rezic.de
# WWW:  http://www.rezic.de/eserte/
#

use strict;
use FindBin;
use Date::Parse;
use Date::Language;
use List::Util qw(max);
use Getopt::Long;

my $skip_wrong = 1;
my $project = "bbbike.de-hosteurope";
my $graph_stage;
my $show;
my $plotter = 'Chart::Gnuplot';
my $width = 1000;
my $height = 700;
GetOptions("skipwrong!" => \$skip_wrong,
	   "project=s" => \$project,
	   "graph=s" => \$graph_stage,
	   'show' => \$show,
	   'plotter=s' => \$plotter,
	   'geometry|geom=s' => sub {
	       ($width,$height) = split /x/, $_[1];
	   },
	  ) 
    or die "usage: $0 [-[no]skipwrong] [-project bbbike.de-hosteurope|www.radzeit.de] [-graph test-from-local|do-rsync|test-on-remote] [-show] [-plotter Chart::Gnuplot|Chart::Clicker]";

my $last_dir = "$FindBin::RealBin/../projects/$project/.last";
my %graph_data;

for my $pairdef ("test-from-local",
		 "do-rsync",
		 "test-on-remote",
		 'deploy-pps',
		) {
    print "\n$pairdef:\n";
    my(@pair) = map { "$last_dir/$_" } ($pairdef eq 'deploy-pps' ? ('start-deploy-pps', 'start-do-rsync') : ("start-$pairdef", $pairdef));

    open my $STARTFH, $pair[0] or die "Can't open $pair[0]: $!";
    open my $STOPFH,  $pair[1] or die "Can't open $pair[1]: $!";

    chomp(my @start = grep { !/^#/ } <$STARTFH>);
    chomp(my @stop  = grep { !/^#/ } <$STOPFH>);

    close $STARTFH;
    close $STOPFH;

    my $dedate = Date::Language->new('German');
    my $endate = Date::Language->new('English');

    my @new_start;
    my @new_stop;
    for my $rundef ([\@start, \@new_start],
		    [\@stop,  \@new_stop],
		   ) {
	my($old, $new) = @$rundef;
	for my $date_line (@$old) {
	    my $date = substr($date_line, 3);
	    my $epoch = $dedate->str2time($date);
	    if (!defined $epoch) {
		$epoch = $endate->str2time($date);
		if (!defined $epoch) {
		    warn "Cannot parse $date_line (using English and German locale), skipping...";
		    next;
		}
	    }
	    push @$new, [$epoch, $date_line];
	}
    }

    for my $stop (@new_stop) {
	my $stop_epoch = $stop->[0];
	my @l = grep { $_->[0] < $stop_epoch } @new_start;
	my $start_epoch = max map { $_->[0] } @l;
	if (!defined $start_epoch) {
	    warn "Cannot determine start for stop time @$stop";
	} else {
	    my $diff = $stop_epoch - $start_epoch;
	    next if ($skip_wrong && $diff > 3600);
	    print "$stop->[1]: $diff\n";
	    if ($graph_stage && $graph_stage eq $pairdef) {
		$graph_data{$stop_epoch} = $diff;
	    }
	}
    }
}

if ($graph_stage) {
    if ($plotter eq 'Chart::Clicker') {
	require Chart::Clicker;
	require Chart::Clicker::Axis::DateTime;
	my $cc = Chart::Clicker->new(width=>$width,height=>$height);
	$cc->add_data('Time-based', \%graph_data);
	$cc->contexts->{default}->domain_axis(Chart::Clicker::Axis::DateTime->new(position => 'bottom', orientation => 'horizontal'));
	$cc->write_output("/tmp/graph.png");
	if ($show) {
	    system 'xzgv', '/tmp/graph.png';
	    unlink '/tmp/graph.png';
	} else {
	    warn "Written to /tmp/graph.png";
	}
    } elsif ($plotter eq 'Chart::Gnuplot') {
	require Chart::Gnuplot;
	my $chart = Chart::Gnuplot->new(
					terminal => "wxt size $width,$height",
					#terminal => "qt size $width,$height",
					title => "analyze_deploy_timestamps: $graph_stage",
					timeaxis => "x",
				       );

	my @datasets;
	{
	    my @data = map { [$_, $graph_data{$_}] } sort { $a <=> $b } keys %graph_data;
	    my $dataset = Chart::Gnuplot::DataSet->new(points => \@data,
						       style => 'lines',
						       timefmt => "%s",
						      );
	    push @datasets, $dataset;
	}
	$chart->plot2d(@datasets);
    } else {
	die "Invalid value for -plotter: must be either Chart::Clicker or Chart::Gnuplot\n";
    }
}

__END__
