#!/usr/bin/env python

import argparse
import json
import os
import socket
from epics import caget

parser = argparse.ArgumentParser(description='Generate full ALH severity state tree for a given subsystem (or all subsystems)')
parser.add_argument('startPV', metavar='STATSUMY', type=str, nargs='?', help='STATSUMY PV to begin trace with. Can be either full SUMY PV name or just subsystem abbreviation (i.e. NTWK or LASR). Searches all subsystems if not specified')
parser.add_argument('-f', '--facility', type=str, default='LCLS', help="facility tree to search under - LCLS, LCLS2, FACET. (default: LCLS)")
parser.add_argument('-o', '--output', type=str, default='./alarmtree.json', help="filename to write Alarm Handler Tree JSON output.  (default: alarmtree.json)")
parser.add_argument('-v', '--verbose', action='store_true', help="Display processing output to STDOUT")
args = parser.parse_args()

subsystems = [ 'GADC', 'FBCK', 'MGNT', 'PROF', 'WS', 'MC', 'LASR', 'RF', 'EVNT', 'NTWK', 'UTIL', 'VAC', 'TEMP', 'MPS', 'PPS', 'BCS', 'MISC' ]

primary = 'ALL'
if args.facility.upper() == 'FACET':
    primary = 'ALLF'
elif args.facility.upper() == 'LCLS2':
    primary = 'ALL2'
    subsystems.append('CRYO')

summaryfield = ':1:STATSUMY'

alarmtrees = []
if args.startPV == None:
    alarmtrees = [ str(primary + ':' + subsys + summaryfield) for subsys in subsystems ]
elif args.startPV.upper() in subsystems:
    alarmtrees.append(primary + ':' + args.startPV.upper() + summaryfield)
else:
    alarmtrees.append(args.startPV)

def get_inputs(sumPV=None):
    '''Find all input PVs in summary CALC'''
    # print 'get_inputs sumPV = {}'.format(sumPV)
    alpha = ['A','B','C','D','E','F','G','H','I','J','K','L']  # Calc PVs only go to INPL currently
    inputs = []
    max_pv_length = 38
    
    sumPV = sumPV.split('.', 1)[0]
    for i in alpha:
        inputPV = sumPV + '.INP' + i
        newinput = caget(inputPV)
        if newinput is None: # stop looking up input PVs if we find a disconnected one
            break
        else:
            newinput = newinput.partition(' ')[0]
            newinput = newinput.split('.', 1)[0]  # Remove field from end of PV name

            # Test if input is being used, bail out once last one is found
            if newinput == "":
                break
            else:
                if len(newinput) >= max_pv_length:
                    if ~newinput.endswith('DP'):
                        if args.verbose:
                            print "Warning! Potential PV length violation for "  + newinput + "!\n   Check for valid PV."
                else:
                    inputs.append(newinput)
    if args.verbose:
        print '{} inputs = {}'.format(sumPV, inputs)
    
    return inputs

def is_summary(pv):
    if pv.find('STATSUMY') >= 0:
        return True
    else:
        return False

def generate_alarm_tree(alarmtree, alarmtop):
    subtree = {}
    if is_summary(alarmtop):
         newinputs = get_inputs(alarmtop)
         if newinputs:
             subtree = { alarmtop: newinputs } 
             for i in newinputs:
                 subtree = generate_alarm_tree(subtree, i)
                 alarmtree[alarmtop] = subtree
    return alarmtree

if __name__ == '__main__':
    alarminputs = []
    alarmtree = {}
    for alarmtop in alarmtrees:
        alarminputs.append(generate_alarm_tree(alarmtree, alarmtop))           
    
    with open(args.output, 'w') as f:
        json.dump(alarminputs, f, indent=4, separators=(',', ': '), sort_keys=True)
        f.write(os.linesep)
