#! /usr/bin/perl

=head1 NAME

myclass_tocollect - students' class collectable files

=head1 SYNOPSIS

 https://server/schulkonsole/myclass_tocollect

=head1 DESCRIPTION

C<myclass_tocollect> lets you upload/download/remove files for your class
from your directory to be collected. The HTML template is myclass_tocollect.tt.

=head2 Template variables

Additionally to the variables of Schulkonsole::Session C<myclass_tocollect>
provides the following variables:

=over

=cut

use strict;
use utf8;
use lib '/usr/share/schulkonsole';
use Schulkonsole::Session;
use Schulkonsole::Info;
use Schulkonsole::Sophomorix;
use File::Basename;

my $this_file = 'myclass_tocollect';
my $transfername = 'upload_'.$this_file;

my $sk_session = new Schulkonsole::Session($this_file);
if (not $sk_session->get_password()) {
	my $q = new CGI;
	my $url = $q->url( -full => 1 );

	# we send cookies over secure connection only:
	if ($url =~ s/^http:/https:/g) {
		$sk_session->redirect($url);
	} else {
		$sk_session->exit_with_login_page($this_file);
	}
}

my $q = $sk_session->query();
my $d = $sk_session->d();

my $classs = Schulkonsole::Info::groups_classes($sk_session->groups());
my $myclass = $sk_session->param('myclass');

if((not $myclass) and $classs){
	my @keys = keys $classs;
	$sk_session->param('myclass',$$classs{$keys[0]});
}

$myclass = $sk_session->param('myclass');

if (   not $myclass  ) {
	my $url = $q->url( -absolute => 1 );
	$url =~ s/$this_file$/myclass/g;
	$sk_session->redirect($url);
}

my $id = $sk_session->userdata('id');
my $password = $sk_session->get_password();

eval {
	SWITCHCOMMAND: {
		$q->param($transfername) and do {
			my $file = $q->param($transfername);
			utf8::decode($file);
			my $tmpfile = "$Schulkonsole::Config::_runtimedir/${transfername}_"
							. $sk_session->session_id() . '_' . time;
			if(! open(DAT,'>'.$tmpfile)) {
				$sk_session->set_status($d->get('Es konnte keine temporäre Datei erzeugt werden.'),1);
				last SWITCHCOMMAND;
			}
			binmode($file);
			binmode(DAT);
			my $buffer = "";
			while( read($file, $buffer, 1024)) {
				print DAT $buffer;
			}
			close(DAT);
			my $filename = basename($file);
			
			Schulkonsole::Sophomorix::add_myclass_tocollect(
				$sk_session->userdata('id'), $sk_session->get_password(), $filename, 0, basename($tmpfile));
			$sk_session->set_status($d->get('Datei hochgeladen'),0);
			
			last SWITCHCOMMAND;	
		}; 
		
		foreach my $param ($q->param) {
			if (my ($file, $action)
			    	= $param =~ /^(.+);(delete|download)$/) {
				utf8::decode($file);
				my $collect_files = Schulkonsole::Sophomorix::ls_myclass_tocollect(
						$sk_session->userdata('id'), $sk_session->get_password());
				
				SWITCHACTION: {
				$action =~ /delete/ and do {
					if(not defined $$collect_files{$file}) {
						$sk_session->set_status(
							$d->get('Datei ') . $file . $d->get(' nicht als einzusammelnde Datei vorhanden.'), 1);
						last SWITCHACTION;
					}
					Schulkonsole::Sophomorix::rm_myclass_tocollect(
						$sk_session->userdata('id'), $sk_session->get_password(),
						$file, ($$collect_files{$file}?1:0));
					
					$sk_session->set_status($d->get('Datei gelöscht.'),0);
					
					last SWITCHACTION;
				};
				
				$action =~ /download/ and do {
					if(not defined $$collect_files{$file}) {
						$sk_session->set_status(
							$d->get('Datei ') . $file . $d->get(' nicht als einzusammelnde Datei vorhanden.'),	1);
						last SWITCHACTION;
					}
					my $tmpfile = "download_${transfername}_".$sk_session->session_id() . '_' . time;
					
					Schulkonsole::Sophomorix::dl_myclass_tocollect(
						$sk_session->userdata('id'), $sk_session->get_password(),
						$file, ($$collect_files{$file}?1:0), $tmpfile);
					
					if( -e "$Schulkonsole::Config::_runtimedir/$tmpfile") {
						print $q->header( -type           => "application/x-download",
								          -attachment     => $file,
										   -Content_length => -s "$Schulkonsole::Config::_runtimedir/$tmpfile");
									
						if(! open(FILE, "<$Schulkonsole::Config::_runtimedir/$tmpfile")) {
							$sk_session->set_status($d->get('Die temporäre Datei konnte nicht geöffnet werden.'), 1);
							last SWITCHCOMMAND;
						}
						binmode(FILE);
						binmode(STDOUT);
						print while <FILE>;
						if(!close(FILE)) {
							$sk_session->set_status($d->get('Die temporäre Datei konnte nicht geschlossen werden.'), 1);
							last SWITCHCOMMAND;
						}
						
						if($$collect_files{$file}){
							system("rm -rf $Schulkonsole::Config::_runtimedir/$tmpfile");
						} else {
							system("rm -f $Schulkonsole::Config::_runtimedir/$tmpfile");
						}
		
						$sk_session->set_status($d->get('Die Datei wurde heruntergeladen.'), 0);
						exit 0;
						
					} else {
						$sk_session->set_status($d->get('Es konnte keine temporäre Datei erzeugt werden.'), 1);
						last SWITCHCOMMAND;				
					}
					
					last SWITCHACTION;
				};
				
				} #SWITCHACTION
			}
		} # foreach param

	} # SWITCHCOMMAND
}; # eval

if ($@) {
	$sk_session->standard_error_handling($this_file, $@);
}










eval {
my $collect_files = Schulkonsole::Sophomorix::ls_myclass_tocollect($id, $password);

=item C<collect_files>

Available files as returned by C<Schulkonsole::Sophomorix::create_file_list()>

=cut

$sk_session->set_var('collect_files',
	Schulkonsole::Sophomorix::create_file_list($collect_files));
};
if ($@) {
	if (    ref $@
		and $@->{code} == Schulkonsole::Error::SophomorixError::WRAPPER_NO_SUCH_DIRECTORY) {
		$sk_session->set_status(
			$sk_session->d()->get('Verzeichnis zum Einsammeln nicht gefunden'),
				1);

		print STDERR "$@\n";
	} else {
		$sk_session->standard_error_handling($this_file, $@);
	}
}



=item C<myclass>

The hash of the users class'

=cut

$sk_session->set_var('myclass', $myclass);

$sk_session->print_page("$this_file.tt", $this_file);
