#!/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 text editor
if os.environ.get("ACE_EDIT_COMMAND"):
    ACE_EDIT_COMMAND = os.environ.get("ACE_EDIT_COMMAND")
else:
    os.putenv("ACE_EDIT_COMMAND", "xemacs")
    ACE_EDIT_COMMAND = "xemacs"

print 'ACE_EDIT_COMMAND: ' + ACE_EDIT_COMMAND
print "Copying " + file_in

EXT=os.path.splitext(sys.argv[1])[1]
EXT = EXT.lower()
temp_filename = os.path.join('acedb' + str(os.getpid()) + EXT)
print temp_filename
shutil.copyfile(file_in, temp_filename)
p_run = subprocess.Popen([ACE_EDIT_COMMAND, temp_filename])
p_run.wait()
#p_run =  subprocess.call([ACE_EDIT_COMMAND, temp_filename])
#print 'Return code = ' + str(p_run)
os.remove(temp_filename)

