package Reader::Holidays;

use strict;

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

    open( $fh, "<$file" ) || die "cannot open holidays file $file: $!"; 
    while( <$fh> ) {
	chomp;
	s/\r//;
	my( $item, $date, $comment ) = split( "," );
	next if( /^#/ || /^$/ || ! $item );
	$item = "holidays:".$item unless( $item =~ /^holidays:/ );
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($self->get_argument("start")); 
	my( $myday, $mymon, $myyear );
	$_ = $date;
	if( /\./ ) {
	    ($myday, $mymon, $myyear) = split( /\./ );
	}
	elsif( /\-/ ) {
	    ($myyear, $mymon, $myday) = split( /\-/ );
	}
	elsif( /\// ) {
	    ($mymon, $myday, $myyear) = split( /\// );
	}
	undef $myyear unless( $myyear =~ /\d/ );
	undef $mymon unless( $mymon =~ /\d/ );
	undef $myday unless( $myday =~ /\d/ );
	if( defined $myyear ) {
	    if( $myyear < 100 ) {
		$myyear += $year - $year%100;
	    }
	    else {
		$myyear -= 1900;
	    }
	}
	next if( ((defined $myday) && ($myday != $mday)) ||
		 ((defined $mymon) && ($mymon != $mon+1)) ||
		 ((defined $myyear) && ($myyear != $year)) );
	$log->push( $item, {
	    "item" => $item,
	    "start" => $self->get_argument( "start" ),
	    "end" => $self->get_argument( "end" ),
	    "status" => "offservice",
	    "comment" => $comment 
	} );
	last;
    }
    close( $fh );
    return $log;
}


1;
