#!/usr/bin/env python3

import subprocess
import tempfile
import os
import shutil
import sys

# This script is called by ACEDB Pick_me_to_call records.
# It copies the file to a temporary file in the current working directory, 
# and then runs the appropriate viewer. After viewing, the 
# temporary file is deleted.  
# $ACE_Viewer is the name of the program. 
# $1 is the file for the program to use.

""" ensure that there are enough command line arguments to parse """
if len(sys.argv) < 2:
    print("Missing FILE parameter");
    print("");
    print("Usage: acePDFviewer.py  FILE");
    exit();

""" get the FILE to open (the first command line argument) """
file_in = sys.argv[1]

if not os.path.exists(file_in):
    print "File \"" + file_in + "\" not found!"

#Choose a .pdf viewer
if os.environ.get("ACE_PDF_COMMAND"):
    ACE_PDF_COMMAND = os.environ.get("ACE_PDF_COMMAND")
else:
    os.putenv("ACE_PDF_COMMAND", "acroread")
    ACE_PDF_COMMAND = "acroread"

print 'ACE_PDF_COMMAND: ' + ACE_PDF_COMMAND
print "Copying " + file_in

#temp_filename = os.path.join(os.getcwd(), 'acedb' + str(os.getpid()) + '.pdf')
temp_filename = os.path.join('acedb' + str(os.getpid()) + '.pdf')
print temp_filename
shutil.copyfile(file_in, temp_filename)
#COMMAND=ACE_PDF_COMMAND + ' ' + temp_filename
#print COMMAND
p_run =  subprocess.Popen([ACE_PDF_COMMAND, temp_filename])
p_run.wait()
#print 'Return code = ' + str(p_run)
#p_run = subprocess.call([COMMAND])
#subprocess.call(['evince', temp_filename], shell=True)
#subprocess.call(['evince acedb5705.pdf'], shell=True)
os.remove(temp_filename)

