#!/usr/local/bin/webwork-perl

## $Id$

# This file is studentSummary.pl
#
# It is called from a form with inputs
# 'user',
#^'key'
# 'course'
# and possibly :
# 		'studentLogin'  (this means the script was called from the utility page by an instructor

# #######################################################################
# Copyright @1996, 1997 by Michael E. Gage and WeBWorK.  All rights reserved.
# #######################################################################

use lib '.'; use webworkInit; # WeBWorKInitLine

#use CGI_Lite;
use CGI qw(:standard);
use Global;
use Auth;
require 5.003;
use strict;

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

&CGI::ReadParse;
my %inputs = %main::in;
#	my %bitbucket = %main::in; # gets rid of -w "used once" error

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


# establish environment for this script
	&Global::getCourseEnvironment($inputs{'course'});
	my	$scriptDirectory   	= $Global::scriptDirectory;
	my	$databaseDirectory 	= $Global::databaseDirectory;
	my	$htmlURL	   		= $Global::htmlURL;
	my	$cgiURL				= $Global::cgiWebworkURL;
	my 	$keyFile = &Global::getCourseKeyFile($inputs{'course'});
	&verify_key($inputs{'user'}, $inputs{'key'}, "$keyFile", $inputs{'course'});

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


# Determine the effective user for this script
	my	$User = $inputs{'user'};   #default

# if this was called from the utilities page
# replace the instructor's login with the desired student's login

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

if ( defined($inputs{'studentLogin'}) ) {  # this means the script is called from the utility page.
	# make sure the user is really an instructor!
	if ($permissions != $Global::instructor_permissions ) {
	    print "permissions = $permissions instructor_permissions = $Global::instructor_permissions\n";
	    print &html_NO_PERMISSION;
	    exit(0);
	    }
	else {

		$User = $inputs{'studentLogin'};
		}
	}

my %setNumberHash = &getAllSetNumbersForStudentLoginHash($User);

# get information on open/due/answer dates for each problem and prepare
# HTML output;

my @SetNumberKeys =  keys(%setNumberHash);
my @problemDates = ();
my $problemDateLine;
my ($probSetKey,$odts,$ddts,$adts,$timeNow,$DueDate,$AnswerDate,$OpenDate);
my $sortedSetNumber;
my $SetNumber;
my %dueTimes =();
my %openTimes =();
my %noOfProbs =();

foreach $SetNumber(@SetNumberKeys) {
    $probSetKey=$setNumberHash{$SetNumber};
    &attachProbSetRecord($probSetKey);
    $odts=&getOpenDate($probSetKey);
    $ddts=&getDueDate($probSetKey);
    $dueTimes{$SetNumber} = $ddts;
    $openTimes{$SetNumber} = $odts;    
    $noOfProbs{$SetNumber} = &getAllProblemsForProbSetRecord($probSetKey);  ##scalar mode gives length of array
}

## Sort setnumbers by due date

    sub by_due_date
        {
        $timeNow = time;
        if ( ($dueTimes{$a} <= $timeNow) and ($dueTimes{$b} <= $timeNow) )
            {
            ($dueTimes{$a} <=> $dueTimes{$b})
                or
            ($a cmp $b)
            }
        elsif ( ($dueTimes{$a} > $timeNow) and ($dueTimes{$b} > $timeNow) )
            {
            ($dueTimes{$a} <=> $dueTimes{$b})
                or
            ($a cmp $b)
            }
        else
            {
            $dueTimes{$b} <=> $dueTimes{$a}
            }

        }


## Find max number of problems in sets

my $maxNoOfProbs = max(values %noOfProbs);

print &htmlTOP("Homework summary for $User");

print qq!

	<A HREF="${cgiURL}welcome.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"> Homework summary for $User</H3>
	<HR SIZE =2>
For each problem a period (.) indicates the problem has not been attempted, a "C" indicates the problem has been answered 
100% correctly, and a number from 0 to 99 indicates the percentage of partial credit earned.  
An "X" indicates the database contains invalid information. <BR><BR>
!;

# Dump the contents of the DBM files:

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



my ($key,@problems,$string,$twoString,@tempSort,
    $total,$totalRight,$status,$longStatus,$valid_status,$msg,$attempted,$probValue,$num,$i);
    
   
print <<EOF;
<TABLE border>
<TR>
<TD ALIGN=center>Set</TD>
<TD ALIGN=center>Status</TD>
<TD ALIGN=center>Score</TD>
<TD ALIGN=center>Out<BR>of</TD>
EOF

##get number of problems    

$string = '<TD ALIGN=center> Problem <BR>';
$twoString = '';
for ($i=1; $i <= $maxNoOfProbs;$i++) {
    $twoString .= &threeSpaceFill($i);
}
$string .= "<pre>$twoString</pre></TD>";
print "$string";

print <<EOF; 

</TR>
EOF

@setList = sort by_due_date @SetNumberKeys;

foreach $SetNumber (@setList) {
    $key = $setNumberHash{$SetNumber};
    &attachProbSetRecord($key)|| print "no Record $key\n";
    $timeNow = time;
    $msg = 'NOT OPEN YET';
    if (($timeNow >= $openTimes{$SetNumber}) and $timeNow < $dueTimes{$SetNumber}) {
        $msg = 'OPEN';
    }
    elsif ($timeNow >= $dueTimes{$SetNumber}) {
         $msg = 'CLOSED';
    }         
    @problems = &getAllProblemsForProbSetRecord($key);
    $string = '';
    @tempSort = sort( { $a <=> $b }  @problems);
    $total=0; $totalRight = 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  ';  
	    }
	    
	    $string  .=  $longStatus;
    	$probValue = &getProblemValue($num,$key);
    	$total += $probValue;   	
    	$totalRight += round_score($status*$probValue) if $valid_status;
    }
    
print <<EOF;
    <TR>
    <TD ALIGN=center>$SetNumber</TD>
    <TD ALIGN=center>$msg</TD>
    <TD ALIGN=center>$totalRight</TD>
	<TD ALIGN=center>$total</TD>    
    <TD ALIGN=left><pre> 
$string</pre></TD> 

    </TR>
EOF

}

print '</TABLE><BR>';

print &htmlBOTTOM('studentSummary.pl', \%inputs);

exit(0);

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