#!/usr/bin/perl
use GD;
use Time::Local;
require "../cgi-lib.pl";
ReadParse(*params);

my %palette;
$maxwidth = 1600;
$maxheight = 800;
$left_offset = 35;
$top_offset = 10;
$bot_offset = 35;
$right_offset = 10;
$img_width = $maxwidth+$left_offset+$right_offset;
$img_height = $maxheight+$top_offset+$bot_offset;
my $img = new GD::Image($img_width,$img_height,1);
$img->fill(1,1,color(255,255,255));

$sdir = "/home/dave/lego/mysets";
opendir(SDIR,$sdir);
@files = readdir(SDIR);
$field = $params{field} || "pieces";

# Counting fold-in from various things. We got married on 2009-05-23, and got the drawers
# from Enfield around 2009-07-??, both in quick proximity.
# We got stuff from Crispin & Steve which was counted partly with Suz's stuff, but that
# Was acquired from sometime perhaps before 2011-05-?? (Brickapalooza meeting was around
# then, so the purchase must have been before? Haven't found a good date for that.

my $fold_date = '20090523';

$minval = 0;
my($extras) = 0;
foreach my $file (@files) {
    next unless($file =~ /^(sets2.txt|sets\d+|\w+setlist.txt)$/);
    my ($data) = parse_list("$sdir/$file");
    if(!$mindate || $data->{date} < $mindate) {
	$mindate = $data->{date};
    }
    if($data->{date} > $maxdate) {
	$maxdate = $data->{date};
	$extras = $data->{fold}{pieces};
    }
    if($data->{$field} > $maxval) {
	$maxval = $data->{$field};
    }
    $points{$data->{date}} = $data;
}
my($daterange) = ($points{$maxdate}{time} - $points{$mindate}{time}) / (24*60*60);

# Adjust each date after the fold-in date as if it had ALL the fold in stuff at that time
foreach my $date (keys %points) {
    if($date >= $fold_date) {
	$points{$date}{pieces} += $points{$maxdate}{fold}{pieces};
	$points{$date}{figs} += $points{$maxdate}{fold}{figs};
	$points{$date}{sets} += $points{$maxdate}{fold}{sets};
	$points{$date}{lots} += $points{$maxdate}{fold}{lots};
	if($points{$date}{$field} > $maxval) {
	    # Fix the maxval after making this adjustment
	    $maxval = $points{$date}{$field};
	}
    }
}

#$img->string(gdTinyFont,30,30,$daterange,color(255,0,0));
#$img->string(gdTinyFont,30,40,$maxval,color(255,0,0));

my($inc) = 100;
for my $i (1,
	   2,
	   5,
	   10,
	   25,
	   50,
	   100,
	   200,
	   250,
	   500,
	   1000,
	   2500,
	   5000,
	   10000,
	   25000,
	   50000,
	   100000,
	   250000,
	   500000,
    ) {
    if(($maxval/$i) > 10 && ($maxval/$i) < 20) {
	$inc = $i;
    }
}
#Now, adjust maxval
if($params{inc}) { $inc = $params{inc}; }
$maxval = (int($maxval/$inc)+1) * $inc;
if($params{maxval}) { $maxval = $params{maxval}; }

for($v=0;$v<=$maxval;$v+=$inc) {
    $y = $maxheight*($v/$maxval);
    $img->line($left_offset,$top_offset+($maxheight-$y),$left_offset+$maxwidth,$top_offset+($maxheight-$y),color(223,223,223));
    $img->string(gdTinyFont,0,$top_offset+($maxheight-$y)-4,$v,color(255,0,0));
}

#$img->string(gdTinyFont,100,40,$inc,color(0,127,0));

my($minyear) = unpack("A4A2A2",$mindate);
my($maxyear) = unpack("A4A2A2",$maxdate);

for(my $year=$minyear+1;$year<=$maxyear;$year++) {
    my($x);
    my($time) = timelocal(0,0,0,1,0,$year-1900);
    $x = $maxwidth * (($time-$points{$mindate}{time}) / ($points{$maxdate}{time}-$points{$mindate}{time}));
    $imgx = $left_offset+$x;
    $img->line($imgx,$top_offset+$maxheight,$imgx,$top_offset,color(255,223,223));
}

foreach my $date (sort {$a<=>$b} (keys %points)) {
    my($x,$y);

    $x = $maxwidth * (($points{$date}{time}-$points{$mindate}{time}) / ($points{$maxdate}{time}-$points{$mindate}{time}));
    $y = $maxheight * ($points{$date}{$field}/$maxval);
    if(-t STDOUT) { print STDOUT "$date - $points{$date}{$field}\n"; }
    $imgx = $left_offset+$x;
    $imgy = $top_offset+($maxheight-$y);

    if($lastx) {
	if(!$lastdatex || ($imgx-$lastdatex) > 15) {
	    $img->line($imgx,$top_offset+$maxheight,$imgx,$top_offset,color(223,223,223));
	    my(@lt) = localtime($points{$date}{time});
	    $lt[5] += 1900;
	    $month = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")[$lt[4]];
	    $month .= "'".substr($lt[5],2,2);
	    $img->stringUp(gdTinyFont,$imgx-4,$top_offset+$maxheight+33,$month,color(255,0,0));
	    $lastdatex = $imgx;
	}
	$img->line($lastx,$lasty,$imgx,$imgy,color(0,127,255));
    } else {
	my(@lt) = localtime($points{$date}{time});
	$lt[5] += 1900;
	$month = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")[$lt[4]];
	$month .= "'".substr($lt[5],2,2);
	$img->stringUp(gdTinyFont,$imgx-4,$top_offset+$maxheight+33,$month,color(255,0,0));
	$lastdatex = $imgx;
    }
    $lastx = $imgx;
    $lasty = $imgy;
}
$img->line($left_offset,$top_offset+$maxheight,$left_offset,$top_offset,color(0,0,0));
$img->line($left_offset,$top_offset+$maxheight,$left_offset+$maxwidth,$top_offset+$maxheight,color(0,0,0));
if($params{fold}) {
    my($diffy) = $maxheight * ($extras/$maxval);
    #$img->string(gdTinyFont,100,100,"$extras,$diffy",color(0,0,0));
    $img->line($left_offset+$maxwidth+5,$top_offset+5,$left_offset+$maxwidth+5,$top_offset+$diffy,color(0,127,255));
}
print "Content-Type: image/png\n\n";
if(-t STDOUT) {
    print "(Skipping image)\n";
} else {
    print $img->png();
}

sub color {
    my($r,$g,$b) = @_;
    $r = standardize($r);
    $g = standardize($g);
    $b = standardize($b);
    if(!defined($palette{"$r\_$g\_$b"})) {
        $palette{"$r\_$g\_$b"} = $img->colorAllocate($r,$g,$b);
    }
    return $palette{"$r\_$g\_$b"};
}

sub standardize {
    my($v) = @_;
    $v = int($v);
    if($v < 0) { $v = 0; }
    if($v > 255) { $v = 255; }
    return $v;
}

sub parse_list {
    my($set_file) = @_;
    my($SETF);
    open($SETF,$set_file) or die "Couldn't open $set_file!\n";
    my($date);
    if($set_file =~ /sets(\d\d\d\d\d\d\d\d)/) {
	$date = $1;
    } elsif($set_file =~ /sets2.txt/) {
	my(@lt) = localtime();
	$date = sprintf("%04d%02d%02d",$lt[5]+1900,$lt[4]+1,$lt[3]);
    } elsif($set_file =~ /collegesetlist/) {
	$date = '19990501';
    } elsif($set_file =~ /oldsetlist/) {
	$date = '19940501';
    }
    my(%totals,%own);
    while(<$SETF>) {
        next unless(/^(\w+|\?+)\t/); #skip comments, blank lines, etc
        chomp;
        my($number,$desc,$pieces,$figs,$qty,$theme,$subthemes) = split /\t/,$_;
       	my($skip) = 0;
	if($desc =~ /\bsuz\b/i && $desc !~ /\b(lugbulk|suz bl)\b/i) {
	    # This stuff all joined the collection at roughly the same time, but was counted gradually
	    # Hence, skip it, but keep track of it. We'll add it in later "all at once"
	    $totals{fold}{figs} += $qty*$figs;
	    $totals{fold}{pieces} += $qty*$pieces;
	    if($number =~ /^\w+$/) {
		$totals{fold}{sets} += $qty;
	    }
	    $totals{fold}{lots} += $qty;
	} else {
	    if($number =~ /^\w+$/) {
		$totals{sets} += $qty;
		$own{$number}++;
	    }
	    $totals{lots} += $qty;
	    $totals{figs} += $qty*$figs;
	    $totals{pieces} += $qty*$pieces;
	}
    }
    $totals{diffsets} = scalar(keys %own);
    $totals{date} = $date;
    my($year,$month,$day) = unpack("A4A2A2",$date);
    my($time) = timelocal(0,0,0,$day,$month-1,$year-1900);
    $totals{time} = $time;
    return \%totals;
}
