package Reader::Cumulator;

use strict;

@Reader::Cumulator::ISA = qw( Reader::Reader );
use StatusLog;
use FileHandle;


sub new {
    my( $this ) = @_;
    my $class = ref($this) || $this;
    my $self = {};
    bless( $self, $class );
    return $self;
}



sub read {
    my( $self ) = @_;
    my $fh = new FileHandle();
    my $ofh = new FileHandle();
    my $file = $self->get_argument( "file" );
    unless( $file ) {
	die "missing file argument, use: ... Cumulator file=filename\n";
    }
    my $start = $self->get_argument( "start" );
    my $end = $self->get_argument( "end" );
    my( $mday, $mon, $year ) = ((localtime( $self->get_argument( "start" ) ))[3,4,5]);
    $year += 1900;
    $mon++;

    my $empty_args = {
	"start" => $start,
	"end" => $end
    }; 
    my $current = Reader::Reader::create( "StatusDB", $empty_args ) -> read();
    my $evaluator = Reader::Reader::create( "Dependency", $empty_args );

    open( $fh, "<$file" ) || die "cannot open cumulator file $file: $!"; 
    while( <$fh> ) {
	chomp;
	s/\r//;
	next if( /^#/ || /^$/ );
	die "invalid specification in $file, line $." unless( /^([a-zA-Z0-9\-\_]+?)[\s\t]*=(.*)$/ );
	my( $class, $base ) = ($1,$2);
	print "cumulating class $class for base $base\n" if( $BigSister::common::dl > 1 );

        my $name = sprintf( "%s/reportdb/day-%04d-%02d-%02d.cumu.%s", 
	    $BigSister::common::fs{'var'}, $year, $mon, $mday, $class );

	#
	# pre-compute our base
	my %evargs = %$empty_args;
	my $basename = "comp:cumubase:$class";
	$evargs{"args"} = ["$basename=$base"];
	$evaluator->set_arguments( \%evargs );
	$evaluator->read();

	open( $ofh, ">$name" ) || die "cannot create cumulator result file $name: $!";
	foreach my $item ($current->get_items()) {
	    next unless( $item =~ /^comp:/ );
	    next if( $item =~ /^comp:_/ );
	    my $rule_item = $item;
	    $rule_item =~ s/^comp:/comp:cumu:/;
	    $evargs{"args"} = ["$rule_item=$item>$basename"];
	    my $log = $evaluator->read();
	    my %colors = ();
	    foreach my $entry (@{$log->get( $rule_item )}) {
		my $duration = $entry->{"end"} - $entry->{"start"};
		my $color = $entry->{"status"};
		$colors{$color} = 0 unless( defined $colors{$color} );
		$colors{$color} += $duration;
	    }
	    while( my( $color, $duration ) = each %colors ) {
		my $item = $item;
		$item =~ s/comp://;
		print $ofh "$item,$color,$duration\n";
	    }
	}
	close( $ofh ) || die "failed to write to $name: $!";
    }
    close( $fh );
    return new StatusLog();
}


1;
