#!/usr/local/bin/perl5 -w

# schedule.pl.cgi

# This script generates an empty presentation schedule and a signup
# form.


### The thing it does:
### 1. generate an empty schedule as a hash with times as keys                       done
### 2. display current schedule from file (save.txt or schedule.txt)                 done
### 3. display the rest of the form                                                  done
### 4. upon submit
###    4.1. if any required fields are missing
###          -> display error message
###    4.2. else 
###          -> calculate required time length from # of participants
###    4.3.     if time (+ length) is not available 
###               -> display error message
###    4.4.     else 
###               -> save new entry to file                                          done
###    4.5.     go back to the beginning (1.)                                        done

$| = 1; #flush output

$data_file = 'schedule.txt';

use CGI qw(:standard);
use POSIX;

$query = new CGI;

print $query->header;
print $query->start_html("Presentation Schedule - Spring 2003");

################ Action to Save on Submit #######################
&save_parameters($query) if $query->param('action') eq 'Submit';

######### Body of page  #################
print <<"EndOfText";
<BODY bgcolor="white">
<P>
<center>
<img src="new-6836-logo.gif">
</center>
<P>
<center>
<img src= "6836-brownline.jpg">
 <P>
<H2>
Presentation Schedule - May 7 and 8, 2003
</H2>
<P>
<img src= "6836-brownline.jpg">
<P>
</center>

To sign up for a presentation slot:<br>
<ol>
<li>Hit the refresh button to see the latest signups
<li>Check the schedule and select an available time slot
<li>Enter your name, title and a very very short abstract (optional)
 <a href="#signup">below</a> and submit the form
</ol>
You should see your presentation next to your chosen time now. Good luck!
<p>
Note: Unfortunately multi-person presentations cannot be entered as
    one at the moment. Please choose time slots adjacent to each other
    and enter your names separately. Please only write the abstract,
    if any, once for every multi-person presentation.
<p>
Note 2: If you can't sign up, it may be that your time slot has
already been taken. Choose another one and try again.
 <P>
This form hasn\'t been tested extensively. If there are any problems
    with it please email <a
    href="mailto:paulina\@ai.mit.edu">paulina</a>. 
<p> 
<center>
EndOfText

############### Start signup form ##########################
print $query->startform;

print <<"EndOfText";

<table border width=100%> 
<th align=center> Wed, May 7 in 2-190</th>
<th align=center> Thu, May 8 in 4-370</th>
</table border>

<TABLE BORDER width=100%>

<TH> Time  </TH> 
<TH> Participants </TH> 
<TH> Title </TH>
<TH> Extremely short abstract  </TH> 
<TH> Time  </TH> 
<TH> Participants </TH>
<TH> Title </TH>
<TH> Extremely short abstract  </TH>

EndOfText

####print "<tr><td>What's going on?</td></tr><br>";

################ Empty form generation #####################
$day1 = "7"; #"Wed, May 7";
$day2 = "8"; #"Thu, May 8";

@times = ();
%time_entries = ();

###print "\ntimes are: @times, time_entries are: %time_entries\n";

for ($i=0; $i<=20; $i++) {
    $t = floor($i/6);
    $hr = 6+$t;
    if ($i) {
	$mn = $i%6;
    } else {
	$mn = 0;
    }

    ## maybe it should be just one index: day:time
    $time_index = "$hr:$mn"."0pm";
#    print "\ntime_index = $time_index <br>";

    push(@times, $time_index);

    $time_entries{$day1,$time_index} = ();
    $time_entries{$day2,$time_index} = ();
}

##print "\n<br>times are: @times<br>\n";

############# Read File and update time_entries ################
&restore_schedule;

###print "\n<br>times are: @times<br>\n";

################ Form entry generation #####################
my $ti;
foreach $ti (@times) {
    print "<tr>\n";
    if (! defined $time_entries{$day1,$ti}) {
	print <<"EndOfText1" ;
	<td>$ti<br>Sign up<br><INPUT type=radio name=\"time\" value=\"7:$ti\"></td>
	<td> </td>
	<td> </td>
	<td> </td>
EndOfText1
    } else {
	$blah = $time_entries{$day1,$ti};
	if ($blah =~ /([\w\W\s]+):([\w\W\s]+):([\w\W\s]*)/) {
	    print <<"EndOfText1" ;
	    <td>$ti</td>
	    <td>$1</td>
	    <td>$2</td>
	    <td>$3</td>
EndOfText1
        } elsif ($blah eq "") {        
	    print "Empty string in entry format, but defined \n<br>";
	} else {
	    print "Something is wrong in the entry format... $blah \n<br>";
	    die ;
	}
    }

    if (! defined $time_entries{$day2,$ti}) {
	print <<"EndOfText2" ;
	<td>$ti<br>Sign up<br><INPUT type=radio name=\"time\" value=\"8:$ti\"></td>
	<td> </td>
	<td> </td>
	<td> </td>
EndOfText2
    } else {
	$blah = $time_entries{$day2,$ti};
	if ($blah =~ /([\w\W\s]+):([\w\W\s]+):([\w\W\s]*)/) {
	    print <<"EndOfText2" ;
	    <td>$ti</td>
	    <td>$1</td>
	    <td>$2</td>
	    <td>$3</td>
EndOfText2
        } elsif ($blah eq "") {        
	    print "Empty string in entry format, but defined \n<br>";
	} else {
	    print "Something is wrong in the entry format... $blah \n<br>";
	    die ;
	}
    }

    print "</tr>\n\n";
} #end foreach $ti of @times


print <<"EndOfText3";
</TABLE BORDER>

<A NAME="signup">
 <P>
<img src= "6836-brownline.jpg">
 <P>
<H2>
Presentation Details
</H2>
 <P>
<img src= "6836-brownline.jpg">
 <P>
<center>

<TABLE cellborder=0 cellpadding=5>

<tr valign = middle>
<td align=left><b>Name</b> </td>
<td>
<INPUT type=text name="name1" size=50><br>
</td></tr>

<tr valign=middle>
<td><b>Title</b></td>
<td><INPUT type=text name="title" size=50 maxlength=100></td>
</tr>

<tr valign=middle>
<td><b>Very Short Abstract</b></td>
<td><TEXTAREA name="abstract" cols=50 rows=6 wrap="virtual"></TEXTAREA></td>
</tr>

<tr valign=middle>
<td></td>
<td align=center>
<INPUT type="submit" name="action" value="Submit">
<INPUT type="reset" name="action" value="Reset">
</td>

</table>

</FORM>


</center>

EndOfText3

print $query->end_html;



#----------------------------- auxiliaries -------------------------#

sub save_parameters {
    local ($query) = @_;
    local ($filename) = $data_file;

    ## all error handling here
    # - a time, a name and a title?
    my $time = $query->param('time');
    my $name1 = $query->param('name1');
    my $title = $query->param('title');
    my $day;
    my $realtime;

    if (!$time or !$name1 or !$title) {
	print "\n<br><STRONG>You must choose a time and provide one"
	. " name and a title of your presentation. Try again.</STRONG><br>\n";
    } else {
	if ($time =~ /^(\d):(\d:\d\dpm)/) {
	    $day = $1;
	    $realtime = $2;
	    if (defined $time_entries{$day,$realtime}) {
		print "\n<br><STRONG> This time slot has already been" .
		    "taken, probably by someone submitting their request at the" .
		    "same time as you. Please choose another one and try again.</STRONG><br>";
	    } else {
		### at this point everything is good with the entry
		if (open(FILE,">>$filename")) {
		    $query->save(FILE);
		    close FILE;
	
#	print "<STRONG>State has been saved to file $filename</STRONG>\n";
		} else {
		    print "<STRONG>Error:</STRONG> couldn't write to file $filename: $!\n";
		}
	    }
	}
    } # end else (if everything is present in the form)
}

sub restore_parameters {
    local ($query) = @_; #not needed
    local ($filename) = $data_file;
    if (open(FILE,$filename)) {
	#generate new query from file, but wait - there's many of them
	while (!eof(FILE)) {
	    my $q = new CGI(FILE);
	    push (@genpage, $q);
	}
	close FILE;
    } else {
	print "<STRONG>Error:</STRONG> couldn't restore from file $filename: $!\n";
    }

    return @genpage; 
}

sub restore_schedule {

    ### call to regenerate webpage from the saved file
    local (@updatedpage) = &restore_parameters;
    my ($day,$time);
    ### restore the full schedule
    foreach $entry (@updatedpage) {
	# what day and time?
	if ($entry->param('time') =~ /^(\d):(\d:\d\dpm)/) {
	    $day = $1;
	    $time = $2;
###	    print "<br>$day $time <br>";
	} else {
	    print "I read: ";
	    print $entry->param('time');
	    print "<br><STRONG>Bad date and time formatting in file</STRONG><br>\n";
	    die;
	}
	### assuming one name per query
	my ($n,$t,$ab) = ($entry->param('name1'),$entry->param('title'),$entry->param('abstract'));

	if (! defined $time_entries{$day,$time}) {
	    $time_entries{$day,$time} = "$n:$t:$ab";
	} else {
	    $ohdear = $time_entries{$day,$time};
#	    print "<br><STRONG>Time entry already taken.</STRONG><br>\n";
#	    die; 
	}
    }

    ## print the whole hash
#    foreach $key (keys %time_entries) {
#	print "<br>$key -> $time_entries{$key} <br>\n";
#    }
}



