#!/usr/bin/env python
import sys
import os
import optparse
import re
# switch from subprocessca to epics.PV because it handles unreachable PVs by returning 'None' 
# if just do "import epics", then must use epics.PV to call PV routines
from epics import PV
import time

# General things
# 1. Instead of "get"ting the PVs each time through the while, could add the "on change" callback
# 2. It takes a LONG time for this script to connect up to all the PVs before the while loop starts, even for only
#    10 global rules and 128 triggers. Could set timeouts on gets to see if this makes it start up faster
# 3. Assumes initial restore of trigger rule ids does not contain duplicates. It only prevents future changes. Checking
#    initial values for duplicates could be done, but it's hard to know what to reject. I.e. do you allow them in order,
#    so that if RULE6 assigned the same global rule as RULE1, the former would be prohibited? or vice versa. By checking
#    only the attempted changes, we let what was in place stand and just reject the request

__all__ = ['build_caput_list', 'process_options']

def build_caput_list(input_path_and_filename,output_path_and_filename=None):

    UNASSIGNED_TRIGGER_RULE_INDICATOR = 'UNASSIGNED'

    # open input file Db/trigs-LI20-thru-LI30
    try:
        in_file = open(input_path_and_filename,"r")
    except IOError, e:
        sys.stderr.write('Could not open "%s": %s\n' % (input_path_and_filename, e.strerror))
        return None

    # open output file Db/caputUnassignedTrigs-LI20-thru-LI30
    try:
        out_file = open(output_path_and_filename,"w")
    except IOError, e:
        sys.stderr.write('Could not open "%s": %s\n' % (output_path_and_filename, e.strerror))
        return None

    print >> out_file, '#!/bin/bash'

    # read in list of triggers from input file
    for line in in_file:
        print line
        # strip off end of line
        line = line.strip()
        # for each trigger, write out 16 lines
        # 8 lines are: 
        out_file.write('caput ')
        out_file.write(line)
        out_file.write(':RULE0.DESC UNASSIGNED\n')
        out_file.write('caput ')
        out_file.write(line)
        out_file.write(':RULE1.DESC UNASSIGNED\n')
        out_file.write('caput ')
        out_file.write(line)
        out_file.write(':RULE2.DESC UNASSIGNED\n')
        out_file.write('caput ')
        out_file.write(line)
        out_file.write(':RULE3.DESC UNASSIGNED\n')
        out_file.write('caput ')
        out_file.write(line)
        out_file.write(':RULE4.DESC UNASSIGNED\n')
        out_file.write('caput ')
        out_file.write(line)
        out_file.write(':RULE5.DESC UNASSIGNED\n')
        out_file.write('caput ')
        out_file.write(line)
        out_file.write(':RULE6.DESC UNASSIGNED\n')
        out_file.write('caput ')
        out_file.write(line)
        out_file.write(':RULE7.DESC UNASSIGNED\n')
 
        # 8 lines are:
        out_file.write('caput -a ')
        out_file.write(line)
        out_file.write(':RULE0 21 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535\n')
        out_file.write('caput -a ')
        out_file.write(line)
        out_file.write(':RULE1 21 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535\n')
        out_file.write('caput -a ')
        out_file.write(line)
        out_file.write(':RULE2 21 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535\n')
        out_file.write('caput -a ')
        out_file.write(line)
        out_file.write(':RULE3 21 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535\n')
        out_file.write('caput -a ')
        out_file.write(line)
        out_file.write(':RULE4 21 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535\n')
        out_file.write('caput -a ')
        out_file.write(line)
        out_file.write(':RULE5 21 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535\n')
        out_file.write('caput -a ')
        out_file.write(line)
        out_file.write(':RULE6 21 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535\n')
        out_file.write('caput -a ')
        out_file.write(line)
        out_file.write(':RULE7 21 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535 65535\n')

    in_file.close        
    out_file.close
    return 0

def process_options(argv):
    # Return parsed command-line options found in the list of
    # arguments, `argv`, or ``sys.argv[1:]`` if `argv` is `None`.

    if argv is None:
        argv = sys.argv[1:]

    usage = 'Usage: %prog input_path output_path_and_file [options]'    
    version = '%prog 0.1'
    parser = optparse.OptionParser(usage=usage, version=version)

    parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='print verbose output')
    parser.add_option("-i", "--input_path", action="store", type="string", dest="input_path", metavar="FILE", help='input path and filename')
    parser.add_option("-o", "--output_file", action="store", type="string", dest="output_file", metavar="FILE", help='output filename (default is stdout)')

    parser.set_defaults(verbose=False,
                        output_file=None)

    (options, args) = parser.parse_args(argv)

    if len(args) < 1:
        parser.error("incorrect number of arguments. args are:  ")

    options.input_path = os.path.normcase(args[0])

    # Kind of weak. Written so that you can't not define output filename and
    # define system_type
    if len(args) > 1: # Absence of output_path_and filename is ok. Uses stdout
        options.output_path_and_filename = os.path.normcase(args[1])
    else:
        options.output_path_and_filename = ''

    return options 


def main(argv=None):
    options = process_options(argv)
    build_caput_list(options.input_path,options.output_path_and_filename)
    return 0


if __name__ == '__main__':
    status = main()
    sys.exit(status)
