package ccbs;
use Template;
use CGI;
use DBI;
use strict;
use warnings;

our $ccbs_dbdebug = 0;
	
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 {
	$ccbs_dbdebug = defined(shift) ? 1 : 0;

	my $dbh = DBI->connect("dbi:Pg:dbname=ccbs;host=sql.samfundet.no", "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 ($ccbs_dbdebug) {
		warn $sql;
		warn "params=" . join(', ', @parms);
	}
	
	my @ret = ();
	while (my $ref = $q->fetchrow_hashref()) {
		if ($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;
	
	my $config = {
		INCLUDE_PATH => 'templates/',
		INTERPOLATE  => 1,
		POST_CHOMP   => 1,
		EVAL_PERL    => 1,
	};
	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', 'Feil',
		{ message => $msg });

	exit;
}

$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 => $msg });
};

1;
