# Description:
# the module implements mechanism of sending messages to wenpanel

########## Confixx(R) 3.0 Professional ############
####### Copyright SWsoft, Inc. 2004-2005 ##########
#### http://www.sw-soft.com - info@sw-soft.com ####


package lib_module_messaging;

BEGIN {
	use Exporter;
	@ISA = 'Exporter';
	@EXPORT = qw( &MySQLEvent &soft_error &hard_error );
}

use lib_module_common;

my ($e_dbh);


if ( ref(lib_module_common::Config) ) {
	&getDbConnect;
}


sub getDbConnect {
	if ($::db_address && $::dbUser ) {
		unless( ref($e_dbh) =~ /DBI/ ) {
			$e_dbh = DBI->connect($::db_address, $::dbUser, $::dbPw )
				or die( &ltext('db_connect', '#XXX', $DBI::errstr) );
		}
	}
}

# MySQLEvent(int code, string message, string anbieter, string kunde)
# writes event to db
# @return void
# writes new event into confixx' log table (db.ereignisse) from
# given values code, message, anbieter, kunde.
# anbieter and kunde are optional
sub MySQLEvent{
  my ($code, $message, $anbieter, $kunde) = @_;
  if($scriptdebug){
    my $subname = (caller(0))[3];
    print "SUB: $subname ($message)\n";
  }
  my $timestamp = time();

  if(!(defined $anbieter)){
    $anbieter = '';
    $kunde = '';

  } elsif( !(defined $kunde) ) {
    $kunde = '';
  }

	&getDbConnect;

	if ( ref($e_dbh)=~/DBI/ ) {

		$e_dbh->do("INSERT INTO ereignisse (timestamp, nachricht, code, script,".
							 " anbieter, kunde) VALUES (?, ?, ?, 'Update-Script', ?, ?)", 
							 undef, $timestamp, $message, $code, $anbieter, $kunde) or 
								 die("error: $DBI::errstr");
		$ereignisse = 1;
	}
}


# hard_error(string message) severe errors routine
# @return die()
# called if error is severe.
# calls MySQLEvent() with code=1 and message, and then
# calls die() with message
sub hard_error {
  if($scriptdebug){
    my $subname = (caller(0))[3];
    print "SUB: $subname\n";
  }
  my ($message) = @_;
  &MySQLEvent(1, $message);
  die($message);
}


# soft_error(string message, string anbieter, string kunde) normal errors routine
# @return void
# calls MySQLEvent().
sub soft_error {
  if($scriptdebug){
    my $subname = (caller(0))[3];
    print "SUB: $subname\n";
  }
  my ($message, $anbieter, $kunde) = @_;

  if ( !(defined $anbieter) ) {
    $anbieter = '';
    $kunde = '';
  } elsif( !(defined $kunde) ) {
    $kunde = '';
  }

  &MySQLEvent(2, $message, $anbieter, $kunde);
}

END {
	if ( ref($e_dbh) =~ /DBI/ ) {
		$e_dbh->disconnect;
		undef $e_dbh;
	}
}

1;

