<?php

require_once(drupal_get_path('module', 'sabreTools') . '/sabreTools.files.inc');
require_once('sabreQMS.files.inc');




/*
 *	simulator_file_download()
 *
 *  implements hook_file_download()
 */

function simulator_file_download($file_id) {
	
  
  try {
    
    if ( user_access('search view reports') == FALSE ) {
      drupal_set_message(t('Unauthorized access.  Unable to access file.'));
      return;
    }


    $file = (object) null;
  
    $sql = "SELECT f.file_uri, f.file_name, s.simulator_id, 
            s.sim_name, s.device_id_internal 
            FROM {qms_simulator_files} f, {qms_simulators} s 
            WHERE f.simulator_id = s.simulator_id AND f.file_id = :fid";
    $results = db_query($sql, array(':fid' => $file_id));
    if ( !$results->rowCount() ) {
      drupal_set_message(t('Oops!  Something went wrong.  Unable to find file.'));
      return;		
    }
    $file = $results->fetchObject();

    $sim_file_dir = 'SIM' . $file->simulator_id;
   
    $base_file_path = variable_get('file_private_path', 'sites/default/files/private' );

    // go up one level (top public_html dir) to access QMS files dir
    $file_path = $base_file_path . '/' . $sim_file_dir . '/' . $file->file_name;


    _st_return_requested_file($file_path);
 
   }
  catch(Exception $e) {
    watchdog('sabreQMS', 'simulator_file_download()' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}


/*
 *	simulator_file_delete_callback()
 *
 *  AJAX call from the browser, deletes file by file_id
 */

function simulator_file_delete_callback($file_id) {
	
	$file_rec = (object) Null;
	
	if ( user_access('administer sabreQMS') ) {	
		
		// find the file the user wants to delete
		$sql = "SELECT file_uri, simulator_id FROM {qms_simulator_files} f WHERE file_id = :fid";
		$result = db_query($sql, array(':fid' => $file_id));
		
		if ( $result->rowCount() ) {
			
			$file_rec = $result->fetchObject();
					
			// how many files are linked to this shift log?
			$result = db_query("SELECT file_id FROM {qms_simulator_files} WHERE simulator_id = :sid",
														array(':sid' => $file_rec->simulator_id));
														
			if ( $result->rowCount() <= 1 ) {
				// after we delete this file, there will be 
				// no more files attached to this shift log, delete the shiftlog's files dir and unset record flag
				
				$num_rows = db_update('qms_simulators')
							->fields(array(
												'files_attached' => 0,
												'updated_date' => time(),
											))
							->condition('simulator_id', $file_rec->simulator_id)
							->execute();						
			}	
			
			_delete_attached_file($file_rec->file_uri);  
			
			// delete the shift log file from the db
			$num_rows = db_delete('qms_simulator_files')
												->condition('file_id', $file_id)
												->execute();										
		}
	}
	
  $content = _get_simulator_files_table($file_rec->simulator_id);
	die($content);
}


/*
 *	_get_simulator_files_table()
 *
 *	refreshes and reformats the files table
 */

function _get_simulator_files_table($simulator_id) {
	
	$bAdmin = user_access('administer sabreQMS');
	
	$table_headers = array(array('data' => 'Files', 'class' => 'qms-files-tbl-col1'),
												 array('data' => 'Uploaded By', 'class' => 'qms-files-tbl-col2'),
												);
	$table_rows = array();

	if ( $bAdmin  ) {
		$table_headers[] = array('data' => 'Options');
	}
	
	$results = _get_simulator_files($simulator_id);	
	
	$i = 0;	
	foreach ( $results as $f ) {	
		$table_rows[] = array( 
      'data' => array( 
          l( t($f->file_name), 
             "simulator/file/download/" . $f->file_id, 
             array('attributes' => array('target'=>'_blank')) ), 
					$f->name . ' - ' . _st_format_date($f->uploaded_timestamp, 'short'),
      ) );		
		if ( $bAdmin ) {
			// admin can edit/delete comments, all done through ajax calls
			$table_rows[$i]['data'][] =  l( t('Delete'), "simulator/file/delete/" . $f->file_id);
		}
		$i++;
	}	
	
	if ( $i == 0 ) {
			$table_rows = array('data' => array('None', ''));
			if ( $bAdmin ) {
				$table_rows['data'][] = '';
			}
	}							
	
	// refresh table
	$content = '<div id="qms-files-tbl-div">';
	$content .= theme( 'table', array(
		'header' => $table_headers,
		'rows' => $table_rows,
	));
	$content .= '</div>';
		
	return $content;
}


/*
 *  _get_simulator_files()
 */
function _get_simulator_files($simulator_id) {
  try {
    
    $sim_files = array();
    
    if ( !$simulator_id ) { return $sim_files; }
    
    // get the record
		$sql = "SELECT f.file_id, u.name, f.uploaded_timestamp, f.file_uri, f.file_name 
              FROM {qms_simulator_files} f, {users} u 
              WHERE f.simulator_id = :sid 
              AND  f.user_id = u.uid  ORDER BY f.file_id";
    $result = db_query($sql, array(':sid' => $simulator_id));	
		
		if ( $result->rowCount() ) {
	    $sim_files = $result->fetchAll();
	  }
    return $sim_files;
  }
  catch (Exception $e) {
    watchdog('sabreQMS', '_get_simulator_files()' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}


/*
 * _get_simulator_file_upload_directory($simulator_id)
 * Returns the name of what the file upload directory should be for this simulator
 * Function exists to standardize the upload directory format
 * the directory name for each set of simulator files is the Simulator Name (sim_name)
 * spaces in the name have been replaced with underscores
 */

function _get_simulator_file_upload_directory($simulator_id) {

	return 'private://' . 'SIM' . $simulator_id;
}

