<?php
/*
 * PiAnoS (Picture Annotation System), A fingerprint examiner training tool
 * Copyright (C) 2011-2021 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 'ping':
                echo 'pong';
                break;
            
            case 'username':
                echo 'noted';
                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 'get_image_data':
            	$id = ( int ) $_GET[ 'id' ];
            	header( "Content-Type: application/json; charset=utf-8" );
                
            	$res = Application::instance()->getDB()->query( "SELECT width, height, resolution FROM image WHERE id = " . pg_escape_string( $id ) . ";" );
            	echo json_encode( $res[ 0 ] );
            	exit();
            	break;
            	
            case 'switchUser':
            	require_once( "backend/changeUserName.php" );
            	if( isset( $_GET[ 'user' ] ) && isset( $_GET[ 'exid' ] ) && isset( $_GET[ 'step' ] ) )
                	changeUser( $_GET[ 'user' ], $_GET[ 'exid' ], $_GET[ 'step' ] );
            	elseif( ! isset( $_GET[ 'user' ] ) && isset( $_GET[ 'exid' ] ) && isset( $_GET[ 'step' ] ) )
                	changeUser( null, $_GET[ 'exid' ], $_GET[ 'step' ] );
            	elseif( isset( $_GET[ 'user' ] ) && isset( $_GET[ 'exid' ] ) )
                	changeUser( $_GET[ 'user' ], $_GET[ 'exid' ] );
            	elseif( isset( $_GET[ 'user' ] ) )
            	    changeUser( $_GET[ 'user' ] );
            	else
            	    changeUser();
        	    
            	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 'upload_image2':
                // TODO: fuse the two cases into one!
                require_once ( "backend/TE/Images.php" );
                header( "Content-Type: application/json; charset=utf-8" );
                try
                {
                    if( count( $_FILES ) == 0 )
                        throw new Exception( "Invalid parameters" );
                    
                    processImageUploads2( NULL, 500 );
                    http_response_code( 200 );
                    
                } catch( Exception $e )
                {
                    echo json_encode( array (
                        'error' => true, 
                        'message' => $e->getMessage() 
                    ) );
                    http_response_code( 500 );
                }
                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;
        }
    }
}
