package Monitor::eventlog;

require 5.001;
use Win32;
use Win32::EventLog;

use strict;
use vars qw(@ISA @EXPORT $VERSION);
use Monitor::logfile;

@ISA = qw(Monitor::logfile);


sub stat {
    return();
}


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

    $self->{"catchupsize"} = 200;
}



sub open {
    my( $self ) = @_;
    my $i;
    my( $file, $host );

    $host = $file = $self->{"file"};
    $host =~ s/:.*//;
    $file =~ s/^.*://;
    $self->{"open"} = $self->{"fh"} = Win32::EventLog->new( $file, "\\\\".$host );
    print "opening EventLog $file on host $host\n" if( $BigSister::common::dl>4 );
    unless( $self->{"open"} ) { return( 0 ); }
    $self->{"_nextevent"} = 1;
    $self->{"fh"}->GetNumber($i);
    $self->{"_max"} = $i;
    return( $self->{"open"} );
}


sub seek {
    my( $self, $pos, $whence ) = @_;

    return(undef) unless( $self->{"open"} );
    if( $whence == 0 ) {
	$self->{"_nextevent"} = $pos;
    }
    elsif( $whence == 1 ) {
	$self->{"_nextevent"} += $pos;
    }
    else {
	my $i;
	$self->{"fh"}->GetNumber($i);
	$i = $i+$pos;
	($i=1) if( $i<1 );
	$self->{"_nextevent"} = $i;
    }
    return 1;
}


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

    return $self->{"_nextevent"};
}


sub readline {
    my( $self ) = @_;
    my( $max, $event );

    unless( $self->{"open"} ) {
	return(undef) unless( $self->open() );
	BigSister::common::log( "err", "established connection to EventLog ".($self->{"file"}) );
    }
    unless( $self->{"fh"}->GetNumber($max) ) {
	BigSister::common::log( "warn", "EventLog GetNumber failed - trying re-open" );
	$self->open();
	unless( $self->{"fh"}->GetNumber($max) ) {
	    BigSister::common::log( "err", "probably lost connection to EventLog ".($self->{"file"}) );
	    return undef;
	}
    }
    if( $max < $self->{"_max"} ) {
	$self->{"_nextevent"} = 1;
    }
    $self->{"_max"} = $max;
    return(undef) if( $self->{"_nextevent"} > $max );
    $self->{"fh"}->Read( (EVENTLOG_SEEK_READ|EVENTLOG_FORWARDS_READ),$self->{"_nextevent"},$event);
    $self->{"_nextevent"}++;
    return $event;
}



sub decode {
    my( $self, $line ) = @_;
    my $computer;

    $computer = $line->{"Computer"};
    $computer =~ tr/A-Z/a-z/;
    return( $line->{"TimeGenerated"}, 
	"EventID=".($line->{"EventID"})."; Source=".($line->{"Source"})."; Severity=".($line->{"EventType"}).": ".($line->{"Message"}), $computer );
}

1;
