#!/usr/bin/env python

################################################################################
# Name: traceAlarm.py                                                          #
# Author: Shawn Alverson                                                       #
# Purpose: Traces alarm tree for invalid status to output alarm progenitors    #
#                                                                              #
# Created: 6/1/2015                                                            #
# Modified:                                                                    #
#                                                                              # 
# Usage: ./traceAlarm <ALH Summary PV>                                         #
#        ex. ./traceAlarm VAC:UND1:1:STATSUMY                                  #
#                                                                              #
################################################################################

import argparse
from socket import gethostname
from epics import caget


# Parse input arguments
parser = argparse.ArgumentParser(description='Trace ALH severity states and output root faults.  Will not output NO_ALARM PVs.')
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('-s', '--severity', type=str, default='ALL',
                    help="severity state to search for - ALL, MINOR, MAJOR, INVALID.  (default is ALL)")
parser.add_argument('-f', '--facility', type=str, default='LCLS',
                    help="facility tree to search under - LCLS or FACET.  (default is LCLS)")
args = parser.parse_args()

# Severities index value increases with overriding state (i.e. MAJOR masks MINOR state in ALH
validStates = [ 'MINOR', 'MAJOR', 'INVALID', 'DISCONNECTED' ]
subsystems = [ 'GADC', 'FBCK', 'MGNT', 'PROF', 'WS', 'MC', 'LASR', 'RF', 'EVNT', 'NTWK',
               'UTIL', 'VAC', 'TEMP', 'MPS', 'PPS', 'BCS', 'MISC' ]

# Decide if searching LCLS, LCLS2, or FACET
if 'facet' in gethostname().lower() or args.facility.upper() =='FACET':
    prim = 'ALLF'
#elif args.facility.upper() =='LCLS2':
#    prim = 'ALL2'
#    subsystems.append('CRYO')
else:
    prim = 'ALL'
    subsystems.append('CRYO')

# Parse Alarm trees to trace
alarmTrees = []
if args.startPV == None:
    for sysName in subsystems:
        alarmTrees.append(prim + ':' + sysName + ':1:STATSUMY')
elif args.startPV.upper() in subsystems:
    alarmTrees.append(prim + ':' + args.startPV.upper() + ':1:STATSUMY')
else:
    alarmTrees.append(args.startPV)


# Parse severities to search for and assign value based on validStated index
traceStates = []
if args.severity.upper() == 'ALL':
    traceState = -1
elif args.severity.upper() in validStates:
    traceState = validStates.index(args.severity.upper())
else:
    print 'PV state ' + args.severity.upper() + ' unknown.  Must be \'MINOR\', \'MAJOR\', \'INVALID\', or \'ALL\'.'
    exit()
    

def getInputs(sumPV=None):
    '''Find all input PVs in summary CALC'''
    
    alpha = ['A','B','C','D','E','F','G','H','I','J','K','L']  # Calc PVs only go p to INPL currently
    inputs = []
    
    sumPV = sumPV.split('.',1)[0]
    for i in alpha:
        inputPV = sumPV + '.INP' + i
        #print 'Getting ' + inputPV + '...'
        newInput = caget(inputPV).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) >= 38:
                if ~newInput.endswith('DP'):
                    print "Warning! Potential PV length violation for "  + newInput + "!\n   Check for valid PV."
            else:
                inputs.append(newInput)

    return inputs

def getFaulted(pv, spacer=''):
    '''Find all inputs to summary PV and check their severity states'''
    
    faults = []
    inputs = getInputs(pv)
    
    if inputs != []:
        for i in inputs:
            #i = i.split('.',1)[0]  # Remove field from end of PV name
            
            if isSummary(i): print spacer + 'Checking state of ' + i
            
            currState = caget(i + '.SEVR', as_string=True)#.upper()
            if (traceState == -1 or traceState >= 2) and currState == None:  # Check for disconnected PV
                faults.append([i,3])
            elif currState == None:
                # PV is disconnected and there is nothing to do about it
                pass
            else:
                if currState.upper() in validStates and validStates.index(currState.upper()) >= traceState:
                    #print i + ' is INVALID!'
                    if isSummary(i):
                        if spacer == '':
                            faults = faults + getFaulted(i,'`--> ')
                        else:
                            faults = faults + getFaulted(i,spacer.split('`-->')[0] + '|    `--> ')
                    elif currState == validStates[traceState] or traceState == -1:
                        faults.append([i,validStates.index(currState)])
    return faults

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


#  Start of main program
if __name__ == '__main__':
    faultedInputs = []
    for alarmTop in alarmTrees:
        if isSummary(alarmTop):
            initialState = caget(alarmTop + '.SEVR', as_string=True).upper()
            if initialState in validStates and validStates.index(initialState) >=  traceState:
                spacer = ''
                faultedInputs += getFaulted(alarmTop, spacer)
            else:
                print alarmTop + " is OK! Nothing to do here..."
        else:
            print alarmTop + ' is not an Alarm Summary!  Nothing to do here...'

    if len(faultedInputs) > 0:
        faultedInputs.sort(key=lambda x: x[1], reverse=True) # Sort list with highest severity on top
        
        print '\nFaulted PVs:'
                
        col_width = max(len(row[0]) for row in faultedInputs) +2 # column padding
        for row in faultedInputs:
            # Pretty-print PVs and states in spaced columns
            print '   ' + row[0].split('.',1)[0][:-2].ljust(col_width) + validStates[row[1]]
        print '\n' # Delineate end of program with final newline

    exit()
        
        


