#!/usr/bin/perl

# creates time-based charts from process-size data:

use lib '/home/raj/perl-lib/ChartDirector/lib';
use perlchartdir;

use IO::All;
use Modern::Perl;
use Data::Printer;

my $file = $ARGV[0] or die "usage: <process_number>.csv";

my @rows = io($file . '.csv')->chomp->slurp; # p @rows; exit;

my %h;
for (@rows) {
    my ($t,$ps) = split ','; # eg 19-03-2016 10:59:19
    
    my ($d,$mon,$y,$h,$min,$s) = $t =~ m!(\d+)-(\d+)-(\d{4}) (\d{2}):(\d{2}):(\d{2})!;
    my $chartTime = perlchartdir::chartTime($y,$mon,$d,$h,$min,$s); # p $chartTime;
    # reduce data points by only using 1 timepoint if >1:
    $h{$chartTime} = $ps; # last one wins
} # p %h; exit; 
    
my %data;    
for (sort keys %h) {
    push @{ $data{labels} }, $_;
    push @{ $data{vals} }, $h{$_};
} # p %h;

{ # time-based graph:
    # Create a XYChart object of size 1250 x 350 pixels
    my $c = new XYChart(1250, 450);

    # Set the plotarea at (80, 20) and of size 1100 x 280 pixels
    $c->setPlotArea(80, 30, 1100, 320);
    $c->xAxis()->setLabelStyle("arial.ttf", 8, 0x000000)->setFontAngle(-45);

    # Add the first data series
    my $layer = $c->addLineLayer2();
    $layer->addDataSet($data{vals});
    $layer->setXData($data{labels});
    $layer->setLineWidth(1);

    # Output the chart
    $c->makeChart($file . '_time.png');
}

{ # event-based graph:
    # Create a XYChart object of size 1250 x 350 pixels
    my $c = new XYChart(1250, 450);

    # Set the plotarea at (80, 20) and of size 1100 x 280 pixels
    $c->setPlotArea(80, 30, 1100, 320);
    $c->xAxis()->setLabelStyle("arial.ttf", 8, 0x000000)->setFontAngle(-45);

    # Set the labels on the x axis
    $c->xAxis()->setLabels2([ 0 .. scalar @{ $data{labels} } - 1 ]);
    $c->xAxis()->setLabelStep(300,10);

    # Add a line layer to the chart
    my $layer = $c->addLineLayer2();

    # Add the data line
    $layer->addDataSet($data{vals});

    # Set the default line width to 1 pixels
    $layer->setLineWidth(1);

    # Output the chart
    $c->makeChart($file . '_event.png');
}
