package Reader::ServiceHours;

use strict;

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

my %days = (
    "so" => 0,
    "su" => 0,
    "mo" => 1,
    "di" => 2,
    "tu" => 2,
    "we" => 3,
    "mi" => 3,
    "th" => 4,
    "do" => 4,
    "fr" => 5,
    "sa" => 6,
    "de" => "*"
);


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: ... ServiceHours file=filename\n";
    }

    open( $fh, "<$file" ) || die "cannot open service hours file $file: $!"; 
    my %list = ();
    while( <$fh> ) {
	chomp;
	s/\r//;
	my( $item, $day, $start, $end, $comment ) = split( "," );
	next if( /^#/ || /^$/ || ! $item );
	$item = "service:".$item unless( $item =~ /^service:/ );
	$start = $self->time( $start );
	$end = $self->time( $end );
	die "invalid time specification in $file, line $." if( $end < $start );
	my $daynum;
	while( my( $abbr, $number ) = each %days ) {
	    if( $day =~ /^$abbr/i ) {
		$daynum = $number;
	    }
	}
	die "day $day is unknown in $file, line $." unless( defined $daynum );
	unless( defined $list{$item} ) {
	    $list{$item} = {};
	}
	unless( defined $list{$item}->{$daynum} ) {
	    $list{$item}->{$daynum} = [];
	}
	push( @{$list{$item}->{$daynum}}, {
	    "start" => $start,
	    "end" => $end,
	    "comment" => $comment
	} );
    }
    close( $fh );

    my $daystart = $self->get_argument( "start" );
    my $dayend = $self->get_argument( "end" );
    my $day = ((localtime( $daystart ))[6]);
    foreach my $item (keys %list) {
	my $daylist;
	if( defined $list{$item}->{$day} ) {
	    $daylist = $list{$item}->{$day};
	}
	elsif( defined $list{$item}->{"*"} ) {
	    $daylist = $list{$item}->{"*"};
	}
	else {
	    next;
	}
	my @sorted = sort { $a->{"start"} <=> $b->{"start"} } @$daylist;
	# add the end of the day
	push( @sorted, {
	    "start" => $dayend-$daystart,
	    "end" => 25*3600
	} );
	my $start = 0;
	while( @sorted ) {
	    my $next = shift @sorted;
	    if( $next->{"start"} > $start ) {
		$log->push( $item, {
		    "item" => $item,
		    "start" => $start + $daystart,
		    "end" => $next->{"start"} + $daystart,
		    "status" => "offservice",
		    "comment" => $next->{"comment"}
		} );
	    }
	    $start = $next->{"end"};
	}
    }
    return $log;
}



sub time {
    my( $self, $text ) = @_;

    return(0) unless( $text );
    unless( $text =~ /^(\d+):(\d+)$/ ) {
	die "invalid time $text in $.";
    }
    return( $1*3600 + $2*60 );
}


1;
