#! /usr/bin/env python

import sys
import time
import epics.pv
from epics.ca import ChannelAccessException
import getopt

def getRetry(Pv, PvName, retries):
    retryCount = 0
    done = False
    value = 0
    while (not done):
        value = Pv.get(None, False, True, 20)
        if (value == None):
            retryCount = retryCount + 1
            print "Retrying " + PvName + "."
            if (retryCount == retries):
                raise "Failed to retrieve " + PvName + " value."
        else:
            done = True
    return value


def testThreshold(thresPv, thresPvName, thres, statePv, statePvName, stateGoodMsg, stateGood,
                  stateBadMsg, stateBad, retries, currentLoss):
    retryCount = 0
    done = False

    while (not done):
        thresPv.put(thres)
        time.sleep(1)
        currentState = getRetry(statePv, statePvName, 5)

        if (verbose):
            sys.stdout.write(str(thresPvName) + "\t= " + str(currentLoss) + " -> " + str(thres) + "\t >>> " + statePvName + " >> ")

        if (currentState == stateGood):
            if (verbose):
                sys.stdout.write(stateGoodMsg)
        else:
            if (verbose):
                sys.stdout.write(stateBadMsg)
            # If epics.PV().get() returns "None" it means there was
            # some problem getting the value
            if (currentState == None):
                if (verbose):
                    sys.stdout.write(" ... failed to get PV value.")
                currentState = stateBad
            
        if (currentState == stateBad):
            if (verbose):
                print "... retry"
        else:
            done = True
            if (verbose):
                print ""

        if (not done):
            if (retryCount >= retries):
                if (verbose):
                    print "FAILED after " + str(retries) + " retries. Check PV " + thresPvName
                done = True
                return False

        retryCount = retryCount + 1

    return True
        
def testChannel(rootPv, thresPv, thresPvName, lossPv, lossPvName, type, results):
    if (verbose):
        print "==== " + rootPv + " " + type + " threshold ===="

    # Get current threshold value
    currentLoss = getRetry(lossPv, lossPvName, 5)
    currentThreshold = getRetry(thresPv, thresPvName, 5)

    # Current channel reading
    if (verbose):
        print lossPvName + "\t= " + str(currentLoss)

    # Current threshold
    if (verbose):
        print thresPvName + "\t= " + str(currentThreshold)
    
    # Define if thresholds should go up or down
    if (type == "low"):
        thresBad = currentLoss + 1
        thresGood = currentLoss - 1
        linkProcessorCurrentState = thresPvName + "_MPSC"
    else:
        thresBad = currentLoss - 1
        thresGood = currentLoss + 1
        linkProcessorCurrentState = thresPvName + "_MPSC"

    linkProcessorCurrentStatePv = epics.PV(linkProcessorCurrentState, None, 'native', None, None, 10, False)
    linkProcessorCurrentStatePv.wait_for_connection(60)

    result={'value':currentLoss,
            'thres_type':type,
            'thres_value':thresGood,
            'fault':'None',
            'result':'FAIL'}
            
    # Write thresholds that don't generate faults
    if (testThreshold(thresPv, thresPvName, thresGood, linkProcessorCurrentStatePv, linkProcessorCurrentState,
                      "IS_OK", 1, "IS_EXCEEDED (FAIL)", 0, 20, currentLoss) == True):
        result['result']='PASS'
        result['fault']='IS_OK'
    else:
        result['result']='FAIL'
        result['fault']='IS_EXCEEDED'        

    results[thresPvName + '-in-limits-' + type] = result
    result['thres_value'] = thresBad

    # Write thresholds that genarate faults
    if (testThreshold(thresPv, thresPvName, thresBad, linkProcessorCurrentStatePv, linkProcessorCurrentState,
                      "IS_EXCEEDED", 0, "IS_OK (FAIL)", 1, 20, currentLoss) == True):
        result['result']='PASS'
        result['fault']='IS_EXCEEDED'        
    else:
        result['result']='FAIL'
        result['fault']='IS_OK'

    results[thresPvName + '-out-limits-' + type] = result

    # Restore original threshold
    thresPv.put(currentThreshold)

    return results

def checkChannel(basePvName, signal, results):
    if (verbose):
        print basePvName + ' ' + signal
    signalPvName = basePvName + ":" + signal
    thresPvName = signalPvName + '_L'

    thresPv = epics.PV(thresPvName, None, 'native', None, None, 30, False)
    thresPv.wait_for_connection(60)
    signalPv = epics.PV(signalPvName, None, 'native', None, None, 30, False)
    signalPv.wait_for_connection(60)
        
    results = testChannel(basePvName, thresPv, thresPvName, signalPv, signalPvName, "low", results)

    thresPvName = signalPvName + '_H'
    thresPv = epics.PV(thresPvName, None, 'native', None, None, 30, False)
    thresPv.wait_for_connection(60)
    
    results = testChannel(basePvName, thresPv, thresPvName, signalPv, signalPvName, "high", results)

    return results


def printResult(channel, result):
    print channel + \
          "\tvalue=" + str(result['value']) + \
          "\tthres_type=" + result['thres_type'] + \
          "\tthres_value=" + str(result['thres_value']) + \
          "\tfault=" + result['fault'] + \
          "\tresult=" + result['result']
          

def usage(cmd):
    print("Usage: %s <opitions>" % cmd)
    print("  -h: print this help")
    print("  -v: verbose")
    print("  -f <file>: text file channels to be tested (one channel per line)")
    print("  -c <channel>: channel to be tested (e.g. BLM:UND1:3021)")
    print("  -s <signal>: PED/LOSS/LOSS_1/LOSS_10/LOSS_30/LOSS_60.")
    print("               If not specified all signals are tested")
    
total = len(sys.argv)
cmdargs = str(sys.argv)

try:
    opts, args = getopt.getopt(sys.argv[1:], "ho:f:c:s:v", ["help", "output="])
except getopt.GetoptError as err:
    # print help information and exit:
    print str(err) # will print something like "option -a not recognized"
    usage(str(sys.argv[0]))
    sys.exit(2)
    
output = None
verbose = False
channelFile = None
channelName = None
signalType = None

for o, a in opts:
    if o == "-v":
        verbose = True
    elif o in ("-h", "--help"):
        usage(str(sys.argv[0]))
        sys.exit()
    elif o in ("-o", "--output"):
        output = a
    elif o in ("-f", "--file"):
        channelFile = a
    elif o in ("-c", "--channel"):
        channelName = a
    elif o in ("-s", "--signal"):
        signalType = a
    else:
        assert False, "unhandled option"
        # ...

results={}
signals=['PED','LOSS','LOSS_1','LOSS_10','LOSS_30','LOSS_60']#,'TEST','TEST_1']
#signals=['PED']

if (channelFile != None):
    f = open(channelFile, "r")
    for line in f:
        basePvName = line.strip()
        if (signalType == None):
            for signal in signals:
                results = checkChannel(basePvName, signal, results)
        else:
            results = checkChannel(basePvName, signalType, results)
    f.close()
    
elif (channelName != None):
    if (signalType == None):
        for signal in signals:
            results = checkChannel(channelName, signal, results)
    else:
        results = checkChannel(channelName, signalType, results)
            
else:
    usage(str(sys.argv[0]));
    sys.exit(-1)
    
failures = False
for key in results.keys():
    if (results[key]['result'] == 'FAIL'):
        failures = True

if (failures == True):
    print("=== TEST FAILED: check the following channels ===")
    for key in results.keys():
        if (results[key]['result'] == 'FAIL'):
            failures = True
            printResult(key, results[key])
    sys.exit(-1)
else:
    print("=== PASSED! ===")


