#!/usr/bin/perl -w
use warnings;
use strict;
use lib '.';
use JSON;
use GD;
use Chart::Clicker;
use GD::Graph::lines;
use GD::Graph::colour qw(:colours);

sub ensureLength {
   my $text = shift;
   my $len = shift;
   my $char = shift;
   #print length($text).":".$len.":".($len - length($text))."\n";
   $text = "".($char x ($len - length($text))).$text if (length($text) < $len);
   return $text;
}

        # Use the biggest-possible list of colors,
        # to avoid reusing the same color.
    my @colors = ();

        #Add some more colors:
        for (my $i = 0; $i < 500; $i++) {
            my $hexcolor = '#';
            for (my $j = 0; $j < 3; $j++) {
               my $num = rand() * 255;
               my $hextext = sprintf("%02x", $num);
               $hexcolor .= $hextext;
            }

            GD::Graph::colour::add_colour($hexcolor);
        }

        my @all_colors = GD::Graph::colour::colour_list();
        # Do not use "white" - that's the same as the background:
        @colors = grep({$_ ne 'white'} @all_colors);


open(DBFILES, "-|", "ls /opt/*/tickets.json") || die($!);
my $x = {};
my $loc = [];
#my @data = ();
while(<DBFILES>) {
   chomp;
   my $dbfile = $_;
   $dbfile =~ m,^\/opt\/([^\/]+)\/,;
   my $id = $1;
   next
      if $id eq "pv"   ||
         $id eq "cmmc" ||
         $id eq "bg"   ||
         $id eq "ovm";
   push(@$loc, $id);
   print $dbfile." -> ".$id."\n";
   open(IN, "<", $dbfile) || die($dbfile.":".$!);
   my $input = <IN>;
   close IN;
   #print "  ".$input."\n";
   eval {
      my $year = undef;
      my $month = undef;
      my $json = undef;
      if ($input && ($json = from_json($input))) {
         foreach my $year (sort {
            $a <=> $b
         } keys %$json) {
            #print STDERR $year."\n";
            foreach my $month (sort {
               $a <=> $b
            } keys %{$json->{$year}}) {
               #print STDERR "  ".$month." ".$json->{$year}->{$month}."\n";
               $x->{$year}->{$month}->{$id} = ref($json->{$year}->{$month}->{dbvalue}) ?
                                                  $json->{$year}->{$month}->{dbvalue} :
                                                  $json->{$year}->{$month};
            }
         }
      }
   };
}

#delete $x->{(localtime(time()))[5]+1900}->{(localtime(time()))[4]+1};

my $data = [];
my $loccount = scalar(@$loc);

push(@$loc, "Average");
push(@$loc, "Sum");

my $cc = Chart::Clicker->new(width => 1200, height => 700, format => 'png');

sub _generate_specific_colors {
    # build the color allocator
    # Add more colors in case your line is more than 6
    my $ca = Chart::Clicker::Drawing::ColorAllocator->new;

    my $red    = Graphics::Color::RGB->new({red => .75, green => 0,   blue => 0,   alpha => .8});
    my $green  = Graphics::Color::RGB->new({red => 0,   green => .75, blue => 0,   alpha => .8});
    my $blue   = Graphics::Color::RGB->new({red => 0,   green => 0,   blue => .75, alpha => .8});
    my $orange = Graphics::Color::RGB->new(red => .88, green => .48, blue => .09, alpha => .8);
    my $aqua   = Graphics::Color::RGB->new(red => 0, green => 1, blue => 1, alpha => .8);
    my $fuchsia = Graphics::Color::RGB->new(red => 1, green => 0, blue => 1, alpha => .8);

    $ca->add_to_colors($green);
    $ca->add_to_colors($red);
    $ca->add_to_colors($blue);
    $ca->add_to_colors($orange);
    $ca->add_to_colors($aqua);
    $ca->add_to_colors($fuchsia);

    return $ca;
}
$cc->color_allocator(_generate_specific_colors);

open(HTML, ">", "out.html") || die($!);

print HTML '
<!DOCTYPE html>
<html>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

<style> 
html, body { 
 height: 100%;
    margin:0;
    padding:0;
}
</style>

<body>
<div id="myPlot" style="width:100%;height:100%"></div>
<script> '."\n";
   my $i = 0;
   foreach my $curloc (@$loc) {
      $i++;
print HTML '
   const c'.$i.'Values = [];
   const x'.$i.'Values = [];
   const y'.$i.'Values = [];'."\n";
}

my $k = 0;
foreach my $year (sort {
   $a <=> $b
} keys %$x) {
    foreach my $month (sort {
       $a <=> $b
    } keys %{$x->{$year}}) {
       $k++;
       next
          unless $year >= 2023;
       push(@{$data->[0]}, $month);
       my $i = 0;
       my $count = 0;
       my $sum = 0;
       foreach my $curloc (@$loc) {
          $i++;
          if ($i <= $loccount) {
             #if ($x->{$year}->{$month}->{$curloc}->{dbvalue}) {
                print HTML 'x'.$i.'Values.push("'.$k.'");'."\n";
                print HTML 'y'.$i.'Values.push("'.($x->{$year}->{$month}->{$curloc}->{dbvalue}||0).'");'."\n";
                print HTML 'c'.$i.'Values.push("'.$year."/".ensureLength($month, 2, "0").'");'."\n";
             #}
             if ($x->{$year}->{$month}->{$curloc}->{dbvalue}) {
                #print "XXX:".$curloc.":".$x->{$year}->{$month}->{$curloc}->{dbvalue}.":\n";
                $cc->add_data($curloc, $x->{$year}->{$month}->{$curloc}->{dbvalue}||0);
                push(@{$data->[$i]},   $x->{$year}->{$month}->{$curloc}->{dbvalue}||0)
             }
          }
          if ($x->{$year}->{$month}->{$curloc}->{dbvalue}) {
             $count++;
             $sum += $x->{$year}->{$month}->{$curloc}->{dbvalue};
          }
       }
       my $avg = int($sum/$count);
       push(@{$data->[$loccount+1]}, $avg);
       push(@{$data->[$loccount+2]}, $sum);
       print HTML 'x'.($loccount+1).'Values.push("'.$k.'");'."\n";
       print HTML 'y'.($loccount+1).'Values.push("'.($avg).'");'."\n";
       print HTML 'c'.($loccount+1).'Values.push("'.$year."/".$month.'");'."\n";
       print HTML 'x'.($loccount+2).'Values.push("'.$k.'");'."\n";
       print HTML 'y'.($loccount+2).'Values.push("'.($sum).'");'."\n";
       print HTML 'c'.($loccount+2).'Values.push("'.$year."/".$month.'");'."\n";
       print "SUM=".$sum." COUNT=".$count." AVG=".$avg." MONTH=".$month." YEAR=".$year."\n";
    }
}
my $defctx = $cc->get_context('default');

#, width: 1200, height: 900, 
print HTML '

//Define Layout
const layout = {title: "'.localtime(time()).'", autosize: true, xaxis: { tickmode: "array", tickvals: x1Values, ticktext: c1Values, font: { size: 18, color: "black"}}};

// Define Data
const data = ['."\n";
   my $j = 0;
   foreach my $curloc (@$loc) {
      $j++;
      print HTML '{'.
         'x: x'.$j.'Values, '.
         'y: y'.$j.'Values, '.
         ' mode:"lines", '.
         #'text: c'.$j.'Values, ',
         'visible: "'.($j > $loccount ? "legendonly" : "yes").'", ',
         'name: "'.$curloc.'"},'.
         "\n";
   }
print HTML '
];

// Display using Plotly
Plotly.newPlot("myPlot", data, layout);
</script>

</body>
</html>';

$defctx->renderer->shape(
    Geometry::Primitive::Circle->new({
       radius => 5,
    })
);

$cc->write_output('foo.png');

my $graph = GD::Graph::lines->new(1200, 900);;

$graph->set( 
    x_label         => 'X Label',
    y_label         => 'Y label',
    title           => 'Tickets',
    long_ticks      => 1,
    y_max_value     => 1400,
    y_tick_number   => scalar(@$loc)+1,
    y_label_skip    => 3,
    bar_spacing     => 3,
    shadow_depth    => 4,
    accent_treshold => 500,
    line_width      => 6,
    dclrs             => \@colors,
    transparent     => 1,
);

# @data = (
#   [ qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct ) ],
#   [ 1, undef, 2, undef, 3, undef, 4, undef, 5, 6 ]
# );
$graph->set_legend_font(gdGiantFont);
$graph->set_legend(@$loc);
my $gd = $graph->plot($data) or die $graph->error;

open(IMG, '>file.png') or die $!;
binmode IMG;
print IMG $gd->png;
