<?php
/*
PiAnoS (Picture Annotation System), A fingerprint examiner training tool
Copyright (C) 2011-2013 University of Lausanne, Switzerland
https://ips-labs.unil.ch/pianos

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see http://www.gnu.org/licenses/.
*/



class MainDriver_TE extends ContentDriver
{
	public function accept()
	{
		return isset($_SESSION['user']);
	}
	
	protected function doHandleRequest()
	{
		if (!isset($_SESSION['user']))
			throw new Exception("Assertion failed");
		
		$action = isset($_GET['action']) ? $_GET['action'] : 'main';
		
		switch ($action)
		{
		case 'main':
		default:
			require_once("backend/TE/MainFrame.php");
			$mainFrame = new MainFrame();
			$this->printHtml($mainFrame);
			break;
		
		case 'take':
			if (!isset($_GET['id']) || (int)$_GET['id'] <= 0)
				throw new Exception("Invalid parameters");
			require_once("backend/TE/TakeExercise.php");
			$mainFrame = new TakeExerciseFrame();
			$this->printHtml($mainFrame);
			break;

		case 'report':
			if ((!isset($_GET['id']) || (int)$_GET['id'] <= 0) && (!isset($_GET['aid']) || (int)$_GET['aid'] <= 0))
				throw new Exception("Invalid parameters");
			require_once("backend/TE/TakeExercise.php");
			$mainFrame = new ExerciseReportFrame();
			$this->printHtml($mainFrame);
			break;

		case 'get_image':
			if (!isset($_GET['id']) || (int)$_GET['id'] <= 0)
				throw new Exception("Invalid parameters");
			require_once("backend/TE/Images.php");
			
			$id = (int)$_GET['id'];
			$thumb = isset($_GET['thumb']);
			$download = isset($_GET['dl']);
			
			sendImage($id, $thumb, $download);
			
			exit;	
			break;

		case 'upload_image':
			require_once("backend/TE/Images.php");
			header("Content-Type: application/json; charset=utf-8");
			try
			{
				if (count($_FILES) == 0)
					throw new Exception("Invalid parameters");

				$ret = processImageUploads(false,NULL,500);
				
				if (count($ret) == 0)
					throw new Exception("No image data received (please retry)");
				if ($ret[0]['error'])
					throw new Exception('While processing image '.$ret[0]['name'].': '.$ret[0]['message']);
					
				echo json_encode(array('error'=>false,'ret'=>$ret[0]['id'],'message'=>$ret[0]['message']));
			}
			catch (Exception $e)
			{
				echo json_encode(array('error'=>true,'message'=>$e->getMessage()));
			}
			exit;	
			break;
			
		case 'export':
		
			parseInputIfJSON();
			
			$formats = array('json','csv');
			
			if (!isset($_POST['format']) || !in_array($_POST['format'], $formats))
				throw new Exception("Invalid parameters (no format specified)");
					
			if (!isset($_POST['data']))
				throw new Exception("Invalid parameters (no data)");

			$isDownload = isset($_POST['delivery']) && $_POST['delivery'] == 'download';

			if ($isDownload && !isset($_POST['exid']) || (int)$_POST['exid'] <= 0)
				throw new Exception("Invalid parameters (no exercise ID)");
			
			if ($_POST['format'] == 'json')
			{
				$input = is_string($_POST['data']) ? $_POST['data'] : json_encode($_POST['data']);
				$output = prettyFormatJSON($input);
				$fileExt = 'json.txt';
				$mimetype = 'text/plain';
			}
			else
			{
				require_once("unil/csvUtils.php");
				$output = "image;user;id;x;y;angle;type;pairing\n";
				$input = is_string($_POST['data']) ? json_decode($_POST['data'],true) : $_POST['data'];
				$imgtypes = array('mark','print');
				$res = Application::instance()->getDB()->query("SELECT id,username FROM person;");
				$unames = array();
				foreach ($res as $person)
					$unames[$person['id']] = $person['username'];
				foreach ($imgtypes as $imgtype)
				{
					if (!array_key_exists($imgtype, $input))
						continue;
					$imgdata = $input[$imgtype]['users'];
					foreach ($imgdata as $uid => $data)
					{
						if (!array_key_exists('minutiae', $data))
							continue;
						$minutiae = $data['minutiae'];
						foreach ($minutiae as $m)
						{
							$pairing = array_key_exists('pairing', $m) ? $m['pairing'] : -1;
							$minutiaID = array_key_exists('oldid',$m) ? $m['oldid'] : $m['id'];
							$mv = array($imgtype, $unames[$uid], $minutiaID, $m['pos'][0], $m['pos'][1], $m['angle'], $m['type'], $pairing);
							$output .= csv_makeline($mv, ";");
						}
					}
				}
				$fileExt = 'csv';
				$mimetype = 'application/csv';
			}

			header("Content-Type: ".$mimetype."; charset=utf-8");
			if ($isDownload)
				header('Content-Disposition: attachment;filename="pianos4_export_ex'.(int)$_POST['exid'].'.'.$fileExt.'"');
			echo $output;
			exit;
			break;
		}
	}
}
