#!/usr/bin/perl -wT
# Listing 2: list-threads.pl

# This is list-threads.pl, which lists the current threads

use strict;
use diagnostics;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use DBI;

my $database = "atf";
my $server = "localhost";
my $port = "3306";
my $username = "reuven";
my $password = "SETME";

# Remove buffering
$| = 1;

# ------------------------------------------------------------
# Create an instance of CGI
my $query = new CGI;

# Send a MIME header
print $query->header("text/html");

print $query->start_html(-title => "Select a thread",
			 -bgcolor => "#FFFFFF");

print "<H1>Select a thread</H1>\n";

print "<P>Clicking on a thread's subject will display the messages ";
print "in that particular discussion.</P>\n";

# ------------------------------------------------------------
# Connect to the database
my $dbh = 
    DBI->connect("DBI:mysql:$database:$server:$port",$username,$password);
die "DBI error from connect: ", $DBI::errstr unless $dbh;

my $sql = "SELECT id,subject FROM ATFThreads ORDER BY subject";

# Send the query
my $sth = $dbh->prepare($sql);
die "DBI error with prepare:", $sth->errstr unless $sth;

# Execute the query
my $result = $sth->execute;
die "DBI error with execute:", $sth->errstr unless $result;

# If we received threads from the SELECT, print them out
if ($sth->rows)
{
    print "<ul>\n";

    # Iterate through thread IDs and names
    while (my @row = $sth->fetchrow)
    {
	print "<li> <a
href=\"/cgi-bin/view-thread.pl?$row[0]\">$row[1]</a>\n";
    }

    print "</ul>\n";

    # Finish that database call
    $sth->finish;
}
else
{
    print "<P>No threads to display!</P>\n";
}

# ------------------------------------------------------------
# Menu bar
print "<P>\n";

# Send the user to the posting form
print "<a href=\"/cgi-bin/post-comment-form.pl\">[Post a message]";
print "</a>\n";

# Send the user to the search
print "<a href=\"/atf/search-form.shtml\">[Search]</a>\n";

# Allow the user to create a new thread
print "<a href=\"/cgi-bin/add-thread-form.pl\">[Add a new
thread]</a>\n";

# Give a plug for the ATF home page
print "<a href=\"/atf/\">[ATF home]</a>\n";

print "</P>\n";

print $query->end_html;

# Disconnect, even though it isn't really necessary
$dbh->disconnect;
