package Reader::ManualOverride;

use strict;

@Reader::ManualOverride::ISA = qw( Reader::Reader );
use StatusLog;
use FileHandle;
use Time::Local;


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();
    my $file = $self->get_argument( "file" );
    unless( $file ) {
	die "missing file argument, use: ... ManualOverride file=filename\n";
    }

    my $start = $self->get_argument( "start" );
    my $end = $self->get_argument( "end" );

    open( $fh, "<$file" ) || die "cannot open override file $file: $!"; 
    while( <$fh> ) {
	chomp;
	s/\r//;
	my( $item, $from, $to, $status, $comment ) = split( "," );
	next if( /^#/ || /^$/ || ! $item );
	$item = "override:".$item unless( $item =~ /^override:/ );
	$from = date( $from );
	$to = date( $to );
	die "invalid date spec. in $file, line $.: end date is earlier than start date" if( $to < $from );
	$from = $start if( $from < $start );
	$to = $end if( $to > $end );
	next if( $from >= $to );
	print "from: ".(scalar localtime($from))." to: ".(scalar localtime($to))."\n" if( $BigSister::common::dl > 1 );
	$log->push( $item, {
	    "item" => $item,
	    "start" => $from,
	    "end" => $to,
	    "status" => $status,
	    "comment" => $comment 
	} );
    }
    close( $fh );
    return $log;
}



sub date {
    my( $dspec ) = @_;

    my( $mon, $mday, $year, $hour, $min, $sec );
    $min = $sec = 0;

    if( $dspec =~ /^(\d+)\.(\d+)\.(\d+)/ ) {
	($mday, $mon, $year) = ($1,$2,$3);
    }
    elsif( $dspec =~ /^(\d{3,4})-(\d+)-(\d+)/ ) {
	($mday, $mon, $year) = ($3,$2,$1);
    }
    elsif( $dspec =~ /^(\d+)-(\d+)-(\d+)/ ) {
	($mday, $mon, $year) = ($1,$2,$3);
    }
    elsif( $dspec =~ /^(\d+)\/(\d+)\/(\d+)/ ) {
	($mday, $mon, $year) = ($2,$1,$3);
    }
    elsif( $dspec =~ /^\d+$/ ) {
	return( $dspec );
    }
    else {
	die "invalid date $dspec at $.";
    }
    if( $year < 100 ) {
	my $lyear = ((localtime())[5]);
	$lyear = $lyear - $lyear%100;
	$year += $lyear;
    }
    else {
	$year -= 1900;
    }

    if( $dspec =~ / (\d+):(\d+)(|:\d+)$/ ) {
	($hour,$min,$sec) = ($1,$2,$3);
	$sec =~ s/://;
	$sec = $sec?$sec:0;
    }
    elsif( $dspec =~ / (\d+):(\d+)(|:\d+)\s*(am|pm)$/i ) {
	my $am;
	($hour,$min,$sec,$am) = ($1,$2,$3);
	$sec =~ s/://;
	$sec = $sec?$sec:0;
	if( ($am =~ /pm/i) && ($hour < 12) ) {
	    $hour += 12;
	}
    }
    else {
	die "invalid time at line $.";
    }

    return timelocal($sec,$min,$hour,$mday,$mon-1,$year);
}

1;
