#! /usr/bin/perl

=head1 NAME

room_test_collect - collect files from users in a room in exam

=head1 SYNOPSIS

 https://server/schulkonsole/room_test_collect

=head1 DESCRIPTION

C<room_test_collect> lets you copy of users in a selected room
to your directory during an exam, or move the files and end the exam.
The HTML template is room_test_collect.tt.

=head2 Template variables

Additionally to the variables of Schulkonsole::Session and
Schulkonsole::Room::set_vars()
C<room_test_collect> provides the following variables:

=over

=cut

use strict;
use utf8;
use lib '/usr/share/schulkonsole';
use Schulkonsole::Room;
use Schulkonsole::Sophomorix;
use Schulkonsole::Session;

my $this_file = 'room_test_collect';


my $sk_session = new Schulkonsole::Session($this_file);
my $q = $sk_session->query();
my $d = $sk_session->d();

my $room_session = new Schulkonsole::Room($sk_session);


if (   not $room_session
    or not $room_session->info('is_editing')) {
	my $url = $q->url( -absolute => 1 );
	$url =~ s/$this_file$/room/g;
	$sk_session->redirect($url);
}



my $workstations
	= Schulkonsole::Config::workstations_room($room_session->info('name'));
my $workstation_users = $room_session->workstation_users();
my %workstation_user_ids;
foreach my $host (keys %$workstations) {
	eval {
	my $login_userdata = Schulkonsole::DB::get_userdata($host);
	next unless $login_userdata;
	$workstation_user_ids{$host} = $$login_userdata{id};
	};
}


eval {
	SWITCHCOMMAND: {
		$q->param('collectmove') and do {
			my $url = $q->url( -absolute => 1 );
			$url =~ s/$this_file$/room_test_end/g;
			$sk_session->redirect($url);
			
			last SWITCHCOMMAND;
		};
		
		$q->param('collectcopy') and do {
			eval {
				Schulkonsole::Sophomorix::collectcopy_exam($sk_session->userdata('id'),
					$sk_session->get_password(),
					$room_session->info('name'));
			
				$sk_session->set_status($sk_session->d()->get('Kopiert'), 0);
			};
			if ($@) {
				$sk_session->standard_error_handling($this_file, $@);
			}
			
			last SWITCHCOMMAND;
		};

		foreach my $param ($q->param) {
			if (my ($file, $action)
			    	= $param =~ /^(.+);(delete|download)$/) {
				utf8::decode($file);
				my $room_collected_files = Schulkonsole::Sophomorix::ls_collected_exam(
						$sk_session->userdata('id'), $sk_session->get_password());
				
				SWITCHACTION: {
				$action =~ /delete/ and do {
					if(not defined $$room_collected_files{$file}) {
						$sk_session->set_status(
							$d->get('Datei ') . $file . $d->get(' nicht als eingesammelte Datei vorhanden.'), 1);
						last SWITCHACTION;
					}
					Schulkonsole::Sophomorix::rm_collected_exam(
						$sk_session->userdata('id'), $sk_session->get_password(),
						$file, ($$room_collected_files{$file}?1:0));
					
					$sk_session->set_status($d->get('Datei gelöscht.'),0);
					
					last SWITCHACTION;
				};
				
				$action =~ /download/ and do {
					if(not defined $$room_collected_files{$file}) {
						$sk_session->set_status(
							$d->get('Datei ') . $file . $d->get(' nicht als eingesammelte Datei vorhanden.'),	1);
						last SWITCHACTION;
					}
					my $tmpfile = "dl_collected_".$sk_session->session_id() . '_' . time;
					my $dlfile = $file;
					
					Schulkonsole::Sophomorix::dl_collected_exam(
						$sk_session->userdata('id'), $sk_session->get_password(),
						$file, ($$room_collected_files{$file}?1:0), $tmpfile);
					if($$room_collected_files{$file}) {
						$tmpfile .= ".zip";
						$dlfile .= ".zip";
					}
					
					if( -e "$Schulkonsole::Config::_runtimedir/$tmpfile") {
						print $q->header( -type           => "application/x-download",
								          -attachment     => $dlfile,
										  -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;
						}
						
						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 $room_collected_files = Schulkonsole::Sophomorix::ls_collected_exam(
	$sk_session->userdata('id'),
	$sk_session->get_password());

=item C<room_collected_files>

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

=cut

$sk_session->set_var('room_collected_files',
	Schulkonsole::Sophomorix::create_file_list($room_collected_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);
	} else {
		$sk_session->standard_error_handling($this_file, $@);
	}
}

eval {
my $user_share_files = Schulkonsole::Sophomorix::ls_collect(
	$sk_session->userdata('id'),
	$sk_session->get_password(),
	values %workstation_user_ids);


my @array_overview_workstations;
foreach my $workstation (sort keys %$workstations) {
	my $first_login = 1;
	if (    $$workstation_users{$workstation}
	    and @{ $$workstation_users{$workstation} }) {
		my $workstation_user_id = $workstation_user_ids{$workstation};

		foreach my $userdata (sort { $$a{uid} cmp $$b{uid} }
		                           @{ $$workstation_users{$workstation} }) {
			my $overview_workstation = {
				name => $workstation,
				login => $$userdata{uid},
				workstationaccount => ($$userdata{uid} eq $workstation),
				first => $first_login,
				files => Schulkonsole::Sophomorix::create_file_list(
				         	$$user_share_files{$workstation_user_id}),
			};
			push @array_overview_workstations, $overview_workstation;

			$first_login = 0;
		}
	}
}

=item C<overview_workstations>

Users logged in on workstations in room as an array of hashes with
the keys

=over

=item C<name>

Name of a workstation

=item C<editing>

True if the logged in user is giving a lesson in the room

=item C<login>

Login of the user

=item C<workstationaccount>

True if the user is logged in via a workstation account

=item C<first>

True if the user is the first of all users on the workstation

=item C<files>

A list of the user's collectable files as returned from
C<Schulkonsole::Sophomorix::create_file_list()>

=back

=cut

$sk_session->set_var('overview_workstations', \@array_overview_workstations);
};
if ($@) {
	$sk_session->standard_error_handling($this_file, $@);
}


$room_session->set_vars($sk_session);

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


=back

=head2 Form fields

=over

=item C<collectcopy>

The files of the workstation users are copied to the current users directory

=item C<collectmove>

Redirect to https://server/schulkonsole/room_test_end

=back

