#!/usr/bin/env python3

# get dawn view of detectors
# W. Armstrong (ANL), original bash script
# C. Peng (ANL), translate to python and add flexible run time for simulation

import os
import subprocess
import argparse
import fcntl


def readline_nonblocking(output):
    fd = output.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
        return output.readline()
    except:
        return ''


# arguments
parser = argparse.ArgumentParser()

parser.add_argument('-c', '--compact-file', type=str, dest='compact',
        default=f'{os.getenv("DETECTOR_PATH")}/{os.getenv("DETECTOR")}.xml',
        help='Top level compact file for detectors')

parser.add_argument('-s', '--skip', type=int,
        default=0,
        help='Number of events number to skip in the input')

parser.add_argument('-i', '--input', type=str, dest='input',
        default='sim_output',
        help='Input hepmc file')

parser.add_argument('-o', '--output-dir', type=str, dest='out_dir',
        default='images',
        help='output directory')

parser.add_argument('-D', '--detector-only', action='store_true', dest='detector_only',
        help='only generate the prim files for the detector geometry')

parser.add_argument('-d', '--dawn-dir', type=str, dest='dawn_dir',
        default='scripts/view1',
        help='Directory to dawn script dir (with .DAWN files and a generate_eps script)')

parser.add_argument('-t', '--tag', type=str,dest='file_tag',
        default='view',
        help='Output file tag')

parser.add_argument('--timeout', type=int,
        default=60,
        help='Timeout in seconds')

parser.add_argument('passthrough', nargs='*')

args = parser.parse_args()

macro = 'macro/dawn_picture.mac' if args.detector_only else 'macro/dawn_picture2.mac'

# raise error if cannot create a temporary working dir
# os.makedirs('dawn_view_tmp', exist_ok=False)
os.makedirs(args.out_dir, exist_ok=True)

# use absolute path so the chdir does not affect them
args.input = os.path.abspath(args.input)
args.out_dir = os.path.abspath(args.out_dir)
args.compact = os.path.abspath(args.compact)
macro = os.path.abspath(macro)

prim_file = 'g4_0000.prim'
dawn_env = os.environ.copy()
dawn_env['DAWN_BATCH'] = 'a'
# sdir = os.path.dirname(os.path.realpath(__file__))


# generate DAWN images
out_dir = os.path.abspath(args.out_dir)
input_file = os.path.abspath(args.input)
#prim_file = '{}/{}.prim'.format(input_dir,args.file_tag)
#prim_file = os.path.abspath(prim_file)
owd = os.getcwd()
os.chdir(args.dawn_dir)
subprocess.run(['pwd'])
subprocess.run(['./generate_eps', '-t', args.file_tag, '-i', input_file] + args.passthrough)
subprocess.run(['ls', '-lrth'])

# upload the results
os.system('cp *.pdf {}'.format(out_dir))
os.system('cp *.png {}'.format(out_dir))
os.chdir(owd)
