#!/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: acedocument.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 viewer
if os.environ.get("ACE_DOCUMENT"):
    ACE_DOCUMENT = os.environ.get("ACE_DOCUMENT")
else:
    os.putenv("ACE_DOCUMENT", "swriter")
    ACE_DOCUMENT = "swriter"

#print 'ACE_DOCUMENT: ' + ACE_DOCUMENT
print "Copying " + file_in


extension = os.path.splitext(file_in)[1]
temp_filename = os.path.join('acedb' + str(os.getpid()) + extension)

#print temp_filename
shutil.copyfile(file_in, temp_filename)
p_run =  subprocess.Popen([ACE_DOCUMENT, temp_filename])
p_run.wait()
#print 'Return code = ' + str(p_run)
os.remove(temp_filename)
