#!/usr/bin/perl

## $Id$

use lib '/ww/webwork/development/'; # mainWeBWorKDirectory;

use Global;
use CGI qw(:standard);
use Auth;
use strict;

# begin Timing code
use Benchmark;
my $beginTime = new Benchmark;
# end Timing code

# local($cgi) = new CGI_Lite();
# local(%inputs) = $cgi->parse_form_data();
&CGI::ReadParse;
my %inputs=%main::in;


&Global::getCourseEnvironment($inputs{'course'});

my $scriptDirectory   = $Global::scriptDirectory;
my $databaseDirectory = $Global::databaseDirectory;
my $htmlURL	   = $Global::htmlURL;
my $cgiURL         = getWebworkCgiURL;

require "${scriptDirectory}$Global::DBglue_pl";
require "${scriptDirectory}HTMLglue.pl";
require "${scriptDirectory}$Global::FILE_pl";

# log access
	&Global::log_info('', query_string);


my $keyFile = &Global::getCourseKeyFile($inputs{'course'});
&verify_key($inputs{'user'}, $inputs{'key'}, "$keyFile", $inputs{'course'});

my $permissionsFile = &Global::getCoursePermissionsFile($inputs{'course'});
my $permissions = &get_permissions($inputs{'user'}, $permissionsFile);

if (($permissions != $Global::instructor_permissions) and ($permissions != $Global::TA_permissions) ) {
	print "permissions = $permissions instructor_permissions = $Global::instructor_permissions\n";
	print &html_NO_PERMISSION;
	exit(0);
	}

###############################################################################
#unless ($inputs{'pCL'}) {
#
#    print &htmlTOP("Classlist: Set Selection for course $inputs{'course'}");
#    print <<EOF;
#<H3 align="center">Welcome to the View Classlist Page</H3>
#On this page, you may choose a problem set whose classlist you would like to view.
#<p><HR>
#Choose a problem set:
#EOF
#
#    print "<form action=\"${cgiURL}classlist.pl\" METHOD = \"POST\">\n";
#   	my  %setNumberHash=&getAllProbSetNumbersHash(
#   									$inputs {'user'});
#    &printProbSetsJR("setNo",\%setNumberHash);
#
#    print "<input type=\"hidden\" name=\"pCL\" value=1>\n";
#    print &sessionKeyInputs(\%inputs);
#    print "<br><input type=\"submit\" value=\"Get Classlist\"></form>";
#    print &htmlBOTTOM("classlist.pl", \%inputs);
#    # begin Timing code
#	my $endTime = new Benchmark;
#	&Global::logTimingInfo($beginTime,$endTime,"classlist.pl",$inputs{'course'},$inputs{'user'});
#	# end Timing code
#    exit;
#}
###############################################################################

print &htmlTOP("Roster for the course $inputs{'course'}, set number $inputs{'setNo'}");
print <<END_OF_HTML;

<A HREF="${cgiURL}profLogin.pl?user=$inputs{'user'}&key=$inputs{'key'}&course=$inputs{'course'}">
<IMG SRC="${Global::upImgUrl}" align="right" BORDER=1 ALT="[Up]"></A><p>
<H3 ALIGN ="CENTER"> Roster and scores for $inputs{'course'}, set $inputs{'setNo'}</H3>
Click on student's name to see  the student's version of the problem set. A period (.) indicates a problem
has not been attempted, a "C" indicates a problem has been answered 100% correctly, and a number from 0 to 99
indicates the percentage of partial credit earned.  The number on the second line gives the number of incorrect attempts.
<HR SIZE =2>
END_OF_HTML

# Dump the contents of the DBM files:

my ($setNum,$psvn,$percentRight,@keyList);

$setNum=$inputs{'setNo'};
my $sortOrder =$inputs{'sortOrder'};

if ($sortOrder eq 'byCourse') {
    @keyList = &getAllProbSetKeysForSetSortedByName($setNum);
}
elsif ($sortOrder eq 'byRecitation') {
    @keyList = &getAllProbSetKeysForSetSortedByRecitationThenByName($setNum);
}
else {
    @keyList = &getAllProbSetKeysForSetSortedBySectionThenByName($setNum);
}
my ($key,$id,$lname,$fname,$login_name,@problems,$string,$twoString,@tempSort,
    $total,$totalRight,$status,$longStatus,$valid_status, $attempted,$probValue,$num,$classSection,$classRecitation,$incorrect,$i);


print <<EOF;
<TABLE border>
<TR>
<TD ALIGN=center COLSPAN=2>Name</TD>
<TD ALIGN=center>psvn</TD>
<TD ALIGN=center>Score</TD>
<TD ALIGN=center>Out<BR>of</TD>
EOF

##get number of problems
&attachProbSetRecord($keyList[0]);
@problems = &getAllProblemsForProbSetRecord($key);
my $noOfProbs = @problems;
$string = '<TD ALIGN=center> Problems <BR>';
$twoString = '';
for ($i=1; $i <= $noOfProbs;$i++) {
    $twoString .= &threeSpaceFill($i);
}
$string .= "<pre>$twoString</pre></TD>";
print "$string";

print <<EOF;
<TD ALIGN=center>section</TD>
<TD ALIGN=center>recitation</TD>
<TD ALIGN=center>login_name</TD>
<TD ALIGN=center>studentId</TD>
</TR>
EOF


foreach $key (@keyList) {
    &attachProbSetRecord($key)|| print "no Record $key\n";
    $id = &getStudentID($key);
    $lname = &getStudentLastName($key);
    $fname = &getStudentFirstName($key);
    $login_name = &getStudentLogin($key);
	$classSection = &getClassSection($key);
	$classRecitation = &getClassRecitation($key);

	# replace empty strings by a non breaking space
	$classSection = '&nbsp;' unless ($classSection =~ /\S/);
	$classRecitation = '&nbsp;' unless ($classRecitation =~ /\S/);	
	
#    $psvn = $key;
    @problems = &getAllProblemsForProbSetRecord($key);
    $string = '';
    $twoString ='';
    @tempSort = sort( { $a <=> $b }  @problems);
    $total=0; $totalRight = 0;
    disable diagnostics;   ## surpress warning caused by ($problemStatus == 0 and $problemStatus ne '0')
    foreach $num (@tempSort) {
        $valid_status = 0;
	    $status = &getProblemStatus($num,$key);
	    $attempted = getProblemAttempted($num,$key);

	    if (!$attempted){
		    $longStatus = '.  ';
	    }
	    elsif   ($status  >= 0 and $status <=1 ) {
	        $valid_status = 1;
	        $longStatus = int(100*$status+.5);
		    if ($longStatus == 100) {
		        $longStatus = 'C  ';
		    }
		    else {
		        $longStatus = &threeSpaceFill($longStatus);
		    }
	    }
	    else	{
		    $longStatus 	= 'X  ';
	    }

	    $incorrect = getProblemNumOfIncorrectAns($num,$key);
	    $incorrect = min($incorrect,99);
	    $string  .=  $longStatus;
	    $twoString .= &threeSpaceFill($incorrect);
    	$probValue = &getProblemValue($num,$key);
    	$total += $probValue;
    	$totalRight += round_score($status*$probValue) if $valid_status;
    }
# save original from 3 lines down     
#    <TD ALIGN=left><A HREF="$Global::welcomeAction_CGI?action=Do_problem_set&user=$inputs{'user'}&course=$inputs{'course'}&key=$inputs{'key'}&probSetKey=$key">$lname</A></TD>

print <<EOF;
    <TR>
    <TD ALIGN=left><A HREF="$Global::welcomeAction_CGI?action=Do_problem_set&user=$inputs{'user'}&course=$inputs{'course'}&key=$inputs{'key'}&local_psvns=$key">$lname</A></TD>
    <TD ALIGN=left>$fname</TD>
    <TD ALIGN=left>$key</TD>
    <TD ALIGN=left>$totalRight</TD>
	<TD ALIGN=left>$total</TD>
    <TD ALIGN=left><pre>$string
$twoString</pre></TD>
	<TD ALIGN=left>$classSection</TD>
	<TD ALIGN=left>$classRecitation</TD>
    <TD ALIGN=left>$login_name</TD>
    <TD ALIGN=left>$id</TD>
    </TR>
EOF

}

print "</TABLE><BR>";

print &htmlBOTTOM("classlist.pl", \%inputs, 'classlistHelp.html');

exit(0);

## subroutines
sub threeSpaceFill {
    my $num = shift @_;
    if ($num < 10) {return "$num".'  ';}
    elsif ($num < 100) {return "$num".' ';}
    else {return "$num";}
}

   