package ccbs;
use Template;
use CGI;
use DBI;
use HTML::Entities;
use Time::HiRes;
use Locale::gettext;
use POSIX;
use strict;
use warnings;
require '../intl/Sesse::GettextizeTemplates.pm';

require '../config.pm';
-r '../config.local.pm' and require '../config.local.pm';

warn "Foo: " . $ccbs::config::lang;
POSIX::setlocale( &POSIX::LC_CTYPE , $ccbs::config::lang );
POSIX::setlocale( &POSIX::LC_MESSAGES , $ccbs::config::lang );
Locale::gettext::bindtextdomain("ccbs", "po");
Locale::gettext::textdomain("ccbs");

our $start_time;

BEGIN {
	$start_time = [Time::HiRes::gettimeofday()];
}

# Hack to get the non-templatized gettext stuff working
*_ = sub {
	return Locale::gettext::gettext(@_);
};

sub print_header {
	print CGI::header(-type=>'text/html; charset=utf-8');
}
sub print_see_other {
	my $location = shift;

	print CGI::header(-status=>'303 See other',
	                  -location=>'http://ccbs.sesse.net/' . $location,
			  -type=>'text/html; charset=utf-8');
}

sub db_connect {
	my $dbh = DBI->connect("dbi:Pg:dbname=ccbs;host=www.positivegaming.com", "ccbs", "GeT|>>B_")
		or die "Couldn't connect to database";
	$dbh->{RaiseError} = 1;
	return $dbh;
}

sub db_fetch_all {
	my ($dbh, $sql, @parms) = @_;
	my $q = $dbh->prepare($sql)
		or die "Could not prepare query: " . $dbh->errstr;
	$q->execute(@parms)
		or die "Could not execute query: " . $dbh->errstr;

	if ($config::ccbs::dbdebug) {
		warn $sql;
		warn "params=" . join(', ', @parms);
	}
	
	my @ret = ();
	while (my $ref = $q->fetchrow_hashref()) {
		if ($config::ccbs::dbdebug) {
			my $dbstr = "";
			for my $k (sort keys %$ref) {
				$dbstr .= " " . $k . "=" . $ref->{$k};
			}
			warn $dbstr;
		}
		push @ret, $ref;
	}

	$q->finish;
	return \@ret;
}
	
sub process_template {
	my ($page, $title, $vars) = @_;
	$vars->{'page'} = $page;
	$vars->{'title'} = $title;
	$vars->{'public'} = $config::ccbs::noadmin;
	$vars->{'timetogenerate'} = sprintf "%.3f", Time::HiRes::tv_interval($start_time);
	
	my $config = {
		INCLUDE_PATH => 'templates/',
		INTERPOLATE  => 1,
		POST_CHOMP   => 1,
		EVAL_PERL    => 1,
		FACTORY      => 'Sesse::GettextizeTemplates'
	};
	my $template = Template->new($config);

	my $output = '';
	$template->process('main.tmpl', $vars, \$output)
		or die $template->error();

	print $output;
}

sub user_error {
	my $msg = shift;

	ccbs::print_header();
	ccbs::process_template('user-error.tmpl', _('Error'),
		{ message => $msg });

	exit;
}
sub admin_only {
	user_error(_("Sorry, the database is in no-admin-mode.")) if ($config::ccbs::noadmin);
}

$SIG{__DIE__} = sub {
	# Gosh! Net::Resolver::DNS is brain-damaged.
	my $msg = shift;
	return if $msg =~ m#Win32/Registry.pm#;

	ccbs::print_header();
	ccbs::process_template('error.tmpl', _('Internal Server Error'),
		{ message => HTML::Entities::encode_entities($msg) });
};

1;
