package Reader::StatusDB;

use strict;

@Reader::StatusDB::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 $log = new StatusLog();
    my $fh = new FileHandle();

    open( $fh, "<".($self->filename()) ); 
    while( <$fh> ) {
	chomp;
	s/\r//;
	my( $item, $start, $end, $status, $comment ) = split( "," );
	$log->push( $item, { 
	    "item" => $item,
	    "start" => $start,
	    "end" => $end,
	    "status" => $status,
	    "comment" => $comment
	} );
    }
    close( $fh );
    return $log;
}


sub dump {
    my( $self, $log ) = @_;
    my $fh = new FileHandle();

    $log->sort();
    open( $fh, ">".($self->filename()) ) || die "cannot create file ".($self->filename()).": $!";
    foreach my $item ($log->get_items()) {
	foreach my $entry (@{$log->get($item)}) {
	    my( $item, $start, $end, $status, $comment ) = (
		$entry->{"item"},
		$entry->{"start"},
		$entry->{"end"},
		$entry->{"status"},
		$entry->{"comment"}
	    );
	    $comment = substr( $comment, 0, 80 );
	    $comment =~ s/,/./g;
	    $comment =~ s/[\n\r]/ /g;
	    print $fh (join( ",", $item, $start, $end, $status, $comment )."\n");
	}
    }
    close( $fh );
}


sub filename {
    my( $self ) = @_;

    my $dir = "$BigSister::common::fs{'var'}/reportdb";
    mkdir( $dir, 0755 ) unless( -d $dir );
    my( $mday, $mon, $year ) = ((localtime( $self->get_argument( "start" ) ))[3,4,5]);
    return( sprintf( "%s/day-%04d-%02d-%02d.statuslog", $dir, $year+1900, $mon+1, $mday ) );
}


1;
