package Massmailer::System;

use strict;
use warnings;
use lib $ENV{'CF_SYSTEM_ROOT'}.'/lib/massmailer/perl', $ENV{'CF_SYSTEM_ROOT'}.'/lib/common/perl';

use Common::Log;
use Massmailer::Config;

our @ISA = ('Exporter');
our @EXPORT = qw(
	connect_db connect_cgp
	sys_log sys_debug_log
	make_die
	get_calls_stack
);


sub connect_db {
	my $dbname = shift or die ("DB name should be specified!");
	my $conntype = shift;## or die ("DB connection type should be specififed!");
	my $dbconn_debug = shift;

	$conntype = 'master'
		unless( defined $conntype );

	$dbname =~ tr/a-z/A-Z/;
	$conntype =~ tr/a-z/A-Z/;
	$conntype = substr($conntype,0,1);

	die("Can't find DB access params for DB=$dbname, conntype=$conntype!")
		unless( defined $CFG_DB->{$dbname}->{$conntype} );

	my $CFG_DB = $CFG_DB->{$dbname}->{$conntype};
	if( defined $dbconn_debug ) {
		use Data::Dumper;
		print STDERR Dumper($CFG_DB);
	}

	use DBI;
	my $dbh = DBI->connect("DBI:mysql:$$CFG_DB{dbname}:$$CFG_DB{dbhost}",$$CFG_DB{'dbuser'},$$CFG_DB{'dbpasswd'},{AutoCommit=>1})
		or make_die ("Can't connect to mysql server: ".$DBI::errstr);

	return $dbh;
}


sub connect_cgp {
	use CLI;
	my $cli = new CGP::CLI({
			'PeerAddr' => $CFG_CGP->{'server'},
			'PeerPort' => $CFG_CGP->{'port'},
			'login'    => $CFG_CGP->{'login'},
			'password' => $CFG_CGP->{'passwd'},
		})
		or make_die ("Can't connect to mail server: ".$!);

	return $cli;
}


sub sys_log {
	my $msg = shift;

	return write_log( SYSTEM_LOG_FNAME, $msg );
}


sub sys_debug_log {
	my $msg = shift;

	return write_log( SYSTEM_DEBUG_LOG_FNAME, $msg );
}


sub make_die {
    my $errmsg = shift;
    $errmsg = '' unless $errmsg;

    my $script_name = $0;

    my $rindex = rindex($script_name,'.');
    $script_name = substr($script_name,0,$rindex) if ($rindex);
    $script_name .= '.log';

    write_log($script_name, $errmsg);

	print STDERR $errmsg."\n";

	exit(0xFF);
}


sub get_calls_stack {
	my $report = '';
	my ($filename, $line, $sub);
	my $i = 0;
	(undef, $filename, $line, $sub, undef, undef) = caller($i++);
	while( $filename ) {
		$report .= "[$i] $filename:$line $sub()\n";
		(undef, $filename, $line, $sub, undef, undef) = caller($i++);
	}

	return $report;
}


1;
