#! /usr/bin/perl -w

use CGI::Carp qw(fatalsToBrowser);
use CGI;
use HTML::Entities;

my $PATH = "/u/d/a/dalibor/public/html/utilities/scribe_signup/";

my $query = new CGI;
if ((uc $ENV{'REQUEST_METHOD'}) eq "POST") {
    if (open DATAFILE, ">>" . $PATH . "signup.dat") {
	# Append to file and close
	print DATAFILE "\"" . $query->param('week') . "\",\"" . $query->param('name') . "\"\n";
	close DATAFILE;

	# Redirect to form
	print "Location: signup.xcgi?done=1\n\n";
    } else {
	# Redirect to form, say things went wrong
	print "Location: signup.xcgi?error=1\n\n";
    }
    
} elsif ((uc $ENV{'REQUEST_METHOD'}) eq 'GET') {
    print<<END;
Content-Type: text/html

<html>
<head>
<link rel=\"StyleSheet\" href=\"styles.css\" />
<title>CS 810 - Scribe Signup</title>
</head>
<body>
END

    # Check for error
    if ($query->param('error')) {
	print '<font color="red">Error inserting your record. Please, try again.</font><br />';	
    } elsif ($query->param('done')) {
	print '<p><font color="green">You have successfully signed up</font></p>';
    }

    # Print table
    print<<END;
<h2>Signup table</h2>
<p>Check the table below (using CTRL+F ... not sorting by week yet) for the week you would like to scribe. If there is at most one name for that week, you can sign up for that week using the <a href="#form">form below</a>. If there are two or more names, that week is taken and the first two people on the list who signed up for that week will scribe that week. If you signed up for something in error, send <a href=\"mailto:dalibor\@cs.wisc.edu\">Dalibor</a> an email and he'll remove that entry from the signup table.</p>
<table>
<tr>
<th>Week</th>
<th>Name</th>
</tr>
END

    my @weeks = ("Week 1: 9/1 - 9/5", 
                 "Week 2: 9/8 - 9/12", 
                 "Week 3: 9/15 - 9/19", 
		 "Week 4: 9/22 - 9/26", 
		 "Week 5: 9/29 - 10/3", 
		 "Week 6: 10/6 - 10/10", 
		 "Week 7: 10/13 - 10/17", 
		 "Week 8: 10/20 - 10/24", 
		 "Week 9: 10/27 - 10/31", 
		 "Week 10: 11/3 - 11/7", 
		 "Week 11: 11/10 - 11/14", 
		 "Week 12: 11/17 - 11/21", 
		 "Week 13: 11/24 - 11/28", 
		 "Week 14: 12/1 - 12/5", 
		 "Week 15: 12/8 - 12/12");
    if (open DATAFILE, $PATH . "signup.dat") {
	while (<DATAFILE>) {
	    my ($week, $name) = $_ =~ /\"(\d{1,2})\",\"(.*)\"/;
	    print "<tr><td>" . $weeks[($week - 1)] . "</td><td>$name</td></tr>\n";
	}
	print "</table>\n";
    } else {
	print "</table>\n";
	print "<p><font color=\"red\">Failed to load table. Please reload the page</font></p>";
    } 

    # Print form
    print<<END;
<h2>Signup Form</h2>
<form id=\"signup\" method=\"POST\" action=\"signup.xcgi\">
<select id=\"week\" name=\"week\">
END

    for ($i = 0; $i < @weeks; $i++) {
	print "<option value=\"" . ($i + 1) . "\">" . $weeks[$i] . "</option>\n";
    }

    print<<END;
</select>
<input type=\"text\" id=\"name\" name=\"name\" />
<input type=\"submit\" id=\"submit\" value=\"Submit\" />
</form>
END
}
