#!/usr/bin/env perl

## This file is profBuildProblemSet.pl
## It provides access to utilities for building problem sets
##

####################################################################
# Copyright @ 1995-1999 University of Rochester
# All Rights Reserved
####################################################################

use lib '.'; use webworkInit; # WeBWorKInitLine
use CGI qw(:standard);

use Global;
use Auth;
use TimeLocal;
use strict;

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

&CGI::ReadParse;
my %inputs =%main::in;

# get information from CGI inputs  (see also below for additional information)

my $Course 			= $inputs{'course'};
my $User 			= $inputs{'user'};
my $Session_key 	= $inputs{'key'};

# verify that information has been received
unless($Course && $User && $Session_key) {
    &wwerror("$0","The script did not receive the proper input data.");
}

# establish environment for this script

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


my $cgiURL   				= getWebworkCgiURL;
# my $courseScriptsDirectory 	= getCourseScriptsDirectory;
my $databaseDirectory 		= getCourseDatabaseDirectory;
my $htmlURL       			= getCourseHtmlURL;
my $scriptDirectory   		= getWebworkScriptDirectory;
my $templateDirectory       = getCourseTemplateDirectory;
my $dat                     = getDat;
my $dd                      = getDirDelim;

require "${scriptDirectory}$Global::DBglue_pl";
require "${scriptDirectory}$Global::FILE_pl";
require "${scriptDirectory}$Global::HTMLglue_pl";
require "${scriptDirectory}$Global::buildProbSetTools";


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


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

#verify session key
	&verify_key($inputs{'user'}, $inputs{'key'}, $keyFile, $inputs{'course'});
		
# verify permissions are correct
	if ($permissions != $Global::instructor_permissions ) {
	    print "permissions = $permissions instructor_permissions = $Global::instructor_permissions\n";
	    print &html_NO_PERMISSION;
	    exit(0);
	    }
# get the rest of the information from the submitted form

my $query = $main::in{CGI};



my $page = $query -> param('page');

if ($page eq 'build') {buildProbSet();}
elsif ($page eq 'destroy') {
    if (getAllowDestroyRebuildProbSets()) {destroyProbSet();}
    else {destroyProbSetNotAllowed();}
}    
else {wwerror($0, "Unknown action: $page");}

    # resume printing the rest of the form

print "<FORM METHOD=POST ACTION=\"${cgiURL}profBuildProblemSetPage.pl\"><P>";
print &sessionKeyInputs(\%inputs);
print <<"ENDOFHTML";
<INPUT TYPE=SUBMIT VALUE="Return to the Build Problem Set Page">
</FORM>
ENDOFHTML

print "<FORM METHOD=POST ACTION=\"${cgiURL}profLogin.pl\"><P>";
print &sessionKeyInputs(\%inputs);
print <<"ENDOFHTML";
<INPUT TYPE=SUBMIT VALUE="Return to the Professor's Page">
</FORM>
ENDOFHTML

print &htmlBOTTOM("profBuildProblemSet.pl", \%inputs);


# begin Timing code
my $endTime = new Benchmark;
&Global::logTimingInfo($beginTime,$endTime,"profBuildProblemSet.pl",$inputs{'course'},$inputs{'user'});
# end Timing code
exit;

sub buildProbSet {

# print HTML text
print &htmlTOP("Build Problem Set");

# print navigation buttons
print qq!
<A HREF="${cgiURL}profBuildProblemSetPage.pl?user=$inputs{'user'}&key=$inputs{'key'}&course=$inputs{'course'}">
<IMG SRC="${Global::upImgUrl}" align="right" BORDER=1 ALT="[Up]"></A><p>
!;

    print <<EOF;
<HR><BR>
<h3 align="left">Information on building the problem set for $Course</h3>
EOF


    ## build problem set

    my @setDefinitionFiles = $query -> param('setDefinition' );
       
#    my $classlistFile = $inputs{'classlist' };
    my $method ='createNewPSVNs';
    my $setDefinitionFile;
    my $outputFormat = $inputs{'outputFormat'};


    foreach $setDefinitionFile (@setDefinitionFiles) {
        my $message = &buildProbSetDB($Course,$setDefinitionFile,$method,'',$outputFormat);
        print "<pre> $message </pre><HR>";
    }    
}


sub destroyProbSet {
    
    if ($inputs{'confirm'}) {

        my $query = $main::in{CGI};
        my @setNumbers = $query -> param('setNo' );       
        my $outputFormat = $inputs{'outputFormat'};
        
        ## first check that all files are readable before deleting any files
#        my $classlistFile = $inputs{'classlist' };
#        wwerror ($0,"Can't read classlist file ${templateDirectory}$classlistFile<BR> No sets destroyed or rebuilt.") 
#          unless -r "${templateDirectory}$classlistFile" ;
        my $setDefinitionFile; 
        my $setNumber;
        foreach $setNumber (@setNumbers) {              
            $setDefinitionFile = "set${setNumber}.def";
            wwerror ($0,"Can't read set definition file ${templateDirectory}$setDefinitionFile<BR> 
            No sets destroyed or rebuilt.") 
              unless -r "${templateDirectory}$setDefinitionFile";
        }
          
        print &htmlTOP("DONE Destroying and Rebuilding Your Problem Set(s)");
    
    
        foreach $setNumber (@setNumbers) {    
            my @PINs=&getAllProbSetKeysForSet($setNumber);
            my @a=<${databaseDirectory}S${setNumber}*>;
    
            print "Deleting problems in set $setNumber<BR>\n";
            print "Problem set keys are: <BR>" if ($outputFormat eq 'all_students');
            my $PIN;
            my $PINcount = 0;
            foreach $PIN (@PINs) {
               &attachProbSetRecord($PIN);
                if (&deleteProbSetRecord($PIN)) {
                    $PINcount++;
                    print ( $PIN, " deleted<BR>\n" ) if ($outputFormat eq 'all_students');
                }
            }
            print "<BR> A total of $PINcount records have been deleted<BR><BR>\n";
            print "deleting .sco files: ${databaseDirectory}S$setNumber-*.sco<BR>";
            system ("rm ${databaseDirectory}S${setNumber}-*.sco");
        
            my $l2hDir = getCoursel2hDirectory();
            print "\ndeleting Latex2html tmp files and the directory:<BR>\n";
            print "     ${l2hDir}set$setNumber<BR>";
            system ("rm -rf ${l2hDir}set$setNumber");
						my $dvipngDir = getCourseTempDirectory()."png/$setNumber";
						print "deleting dvipng tmp files and the directory:<BR>\n";
            print "     $dvipngDir<BR>";
						system ("rm -rf $dvipngDir");
            print '<HR>';
        }
        print "<H1><B>DONE DELETING SETS</B></H1>";
        
        print <<EOF;
<HR><BR>
<h3 align="left">Information on building the problem set for $Course</h3>
EOF
        
        my $method ='createNewPSVNs';
        $outputFormat = $inputs{'outputFormat'};

        foreach $setNumber (@setNumbers) {  
            
            $setDefinitionFile = "set${setNumber}.def";
            my $message = &buildProbSetDB($Course,$setDefinitionFile,$method,'',$outputFormat);
            print "<pre> $message </pre><HR>";
            $outputFormat = 'no_students';  ## if format is all_students, only list them the first time.
        }
        print "<H1><B>DONE REBUILDING SETS</B></H1>";                 
    }
    else {
        print &htmlTOP("NO Set(s) were destroyed");
        print "No sets were destroyed since Destroy and Rebuild was not enabled. If you want to delete sets, go back and select
          &quot;Destroy and Rebuild enabled&quot; before deleing the sets.<BR>";  
        print "<H1><B>NO SETS DESTROYED</B></H1>";    
    }    
}      

sub destroyProbSetNotAllowed {

        print &htmlTOP("NO Set(s) were destroyed");
        print "<b>No sets were destroyed. Destroy and Rebuild is not allowed for this course</b><p>";
        
        print "When allowed a professor can destroy and  rebuild problems sets in one operation. 
        This is very convenient and powerful, but also very dangerous.  Usually this is not 
        allowed in courses students are using.  It is often allowed in a private course being 
        used only for developing problem sets.<p>";
        
        print "If you really want to destroy and rebuild sets, you have two options.  Option one is to
        first delete the set(s) (goto the Delete Problem set page) and then build the set(s) again.
        Option two is to enable Destroy and Rebuild for this course. To do that, edit the webworkCourse.ph
        file setting <BR><BR>
        <code>\$allowDestroyRebuildProbSets = 1 </code>";
        
  
        print "<H1><B>NO SETS DESTROYED</B></H1>"; 
        
        print "<FORM METHOD=POST ACTION=\"${cgiURL}profDeleteProbSet.pl\"><P>";
print &sessionKeyInputs(\%inputs);
print <<"ENDOFHTML";
<INPUT TYPE=SUBMIT VALUE="Go to the Delete Problem Set Page">
</FORM>
ENDOFHTML
}
