#!/usr/bin/env python
import subprocess
import argparse
from epics import PV
import time
import sys 
import datetime
import getpass

def writeLine(line, report):
    sys.stdout.write(line)
    report += line
    return report

def reportTestResult(report, failures):
    report = writeLine("\n", report)
    report = writeLine("\n", report)
    report = writeLine("===================================================\n", report)
    report = writeLine("=== TEST RESULT:\n", report)
    if (len(failures) > 0):
        i = 1
        report = writeLine("=== *** FAILED FAILED FAILED FAILED FAILED FAILED ***\n", report)
        for failure in failures:
            report = writeLine('=== {0}) {1}'.format(i, failure), report)
            i = i + 1
    else:
        report = writeLine("=== PASSED PASSED PASSED PASSED PASSED PASSED :)\n", report)

    report = writeLine("===================================================\n\n", report)

    return report

def testCamera(pvBase, report, failures, stepCount):
    report = writeLine('### Testing camera power ###\n', report)
    powerPv = PV(pvBase + ":CAMERA_PWR")

    report = writeLine('  {0}) Camera power OFF... '.format(stepCount), report)
    stepCount = stepCount+1
    powerPv.put(0)
    report = writeLine(" done.\n", report)

    report = writeLine('  {0}) Camera power ON... '.format(stepCount), report)
    stepCount = stepCount+1
    powerPv.put(1)

    cmd='zenity --question --ok-label="YES" --cancel-label="NO" --text="Is camera power on?"'
    p=subprocess.Popen(cmd, shell=True)
    streamdata=p.communicate()[0]
    rc=p.returncode
    if (rc != 0):
        report = writeLine('  *** ERROR *** Camera power not on - visually verified.\n', report)
        failures.append('Camera power not on (step {0})\n'.
                        format(stepCount))

    else:
        report = writeLine(" done.\n", report)
    stepCount = stepCount+1

    report = writeLine('  {0}) Camera power OFF... '.format(stepCount), report)
    stepCount = stepCount+1
    powerPv.put(0)
    report = writeLine(" done.\n", report)

#    failures.append("blabla\n")

    return report, failures, stepCount
    

def testMotor(motorName, motorIndex, pvBase, report, failures, stepCount):
    report = writeLine('### Testing {0} motor ###\n'.format(motorName), report)
    
    selectPv = PV(pvBase + ":LENS_MOTR_FUNC")
    cwPv = PV(pvBase + ":LENS_MOTR_CTRL_CW")
    ccwPv = PV(pvBase + ":LENS_MOTR_CTRL_CCW")

    # Select Motor
    report = writeLine('  {0}) Selecting {1} motor... '.
                       format(stepCount, motorName), report)
    stepCount = stepCount+1
    selectPv.put(motorIndex)
    report = writeLine(" done.\n", report)

    # Move CW
    report = writeLine('  {0}) Moving {1} motor clockwise... '.
                       format(stepCount, motorName), report)
    cwPv.put(1)
    time.sleep(5)
    cwPv.put(0)

    cmd='zenity --question --ok-label="YES" --cancel-label="NO" --text="Has {0} motor moved clockwise?"'.format(motorName)
    p=subprocess.Popen(cmd, shell=True)
    streamdata=p.communicate()[0]
    rc=p.returncode
    if (rc != 0):
        report = writeLine('  *** ERROR *** {0} motor did not move CW direction - visually verified.\n'.format(motorName), report)
        failures.append('{0} motor did not move CW (step {1})\n'.
                        format(motorName, stepCount))
    else:
        report = writeLine(" done.\n", report)
    stepCount = stepCount+1

    # Move CCW
    report = writeLine('  {0}) Moving {1} motor counter clockwise... '.
                       format(stepCount, motorName), report)
    stepCount = stepCount+1
    ccwPv.put(1)
    time.sleep(2)
    ccwPv.put(0)
    report = writeLine(" done.\n", report)

    # Unselect Motor
    report = writeLine('  {0}) Selecting no motor... '.
                       format(stepCount), report)
    stepCount = stepCount+1
    selectPv.put(0)

    cmd='zenity --question --ok-label="YES" --cancel-label="NO" --text="Has {0} motor moved counter clockwise?"'.format(motorName)
    p=subprocess.Popen(cmd, shell=True)
    streamdata=p.communicate()[0]
    rc=p.returncode
    if (rc != 0):
        report = writeLine('  *** ERROR *** {0} motor did not move CCW direction - visually verified.\n'.format(motorName), report)
        failures.append('{0} motor did not move CCW (step {1})\n'.
                        format(motorName, stepCount))

    else:
        report = writeLine(" done.\n", report)
    stepCount = stepCount+1

    return report, failures, stepCount

# testLamp('Target', 'TGT', args.d[0], args.i[0])
def testLamp(deviceName, devicePvSuffix, pvBase,
             viocPvBase, report, failures, stepCount):
    report = writeLine('### Testing {0} lamp ###\n'.format(deviceName), report)
    powerPv = PV(pvBase + ":" + devicePvSuffix + "_LAMP_PWR")
    controlPv = PV(viocPvBase + ":" + devicePvSuffix + "_LAMP_CTRL")

    # Turn Lamp off and set voltage to zero
    report = writeLine('  {0}) {1} lamp off and no brightness... '.
                       format(stepCount, deviceName), report)
    stepCount = stepCount+1
    powerPv.put(0)
    controlPv.put(0)
    report = writeLine(" done.\n", report)

    report = writeLine('  {0}) {1} lamp on... '.format(stepCount, deviceName), report)
    stepCount = stepCount+1
    powerPv.put(1)
    report = writeLine(" done.\n", report)

    report = writeLine('  {0}) {1} lamp brightness up... '.
                       format(stepCount, deviceName), report)
    for i in range(0,10):
        controlPv.put(i)
        time.sleep(0.25)

    cmd='zenity --question --ok-label="YES" --cancel-label="NO" --text="Is {0} lamp fully lit?"'.format(deviceName)
    p=subprocess.Popen(cmd, shell=True)
    streamdata=p.communicate()[0]
    rc=p.returncode
    if (rc != 0):
        report = writeLine('  *** ERROR *** {0} lamp not fully lit - visually verified.\n'.format(deviceName), report)
        failures.append('{0} Lamp FAILED full brightness (step {1})\n'.
                        format(deviceName, stepCount))

    else:
        report = writeLine(" done.\n", report)
    stepCount = stepCount+1

    report = writeLine('  {0}) {1} lamp brightness down... '.format(stepCount, deviceName), report)
    stepCount = stepCount+1
    for i in range(10, -1, -1):
        controlPv.put(i)
        time.sleep(0.25)
    report = writeLine(" done.\n", report)

    report = writeLine('  {0}) {1} lamp off... '.format(stepCount, deviceName), report)
    powerPv.put(0)
    cmd='zenity --question --ok-label="YES" --cancel-label="NO" --text="Is ' + deviceName + ' lamp off?"'
    p=subprocess.Popen(cmd, shell=True)
    streamdata=p.communicate()[0]
    rc=p.returncode
    if (rc != 0):
        report = writeLine('  *** ERROR *** {0} lamp not fully off - visually verified.\n'.format(deviceName), report)
        failures.append('{0} Lamp FAILED no brightness (step {1})\n'.
                        format(deviceName, stepCount))

    else:
        report = writeLine(" done.\n", report)
    stepCount = stepCount+1
        
    return report, failures, stepCount

def testInsertionDeviceOperation(deviceName, operationName,
                                 expectedOutValue, expectedInValue, expectedStatusValue, controlValue,
                                 outPv, inPv, statusPv, controlPv, report, failures, stepCount):
    # Control device
    report = writeLine('  {0}) {1} {2}... '.format(stepCount, operationName, deviceName), report)
    stepCount = stepCount+1
    sys.stdout.flush()
    controlPv.put(controlValue)
    time.sleep(2)
    report = writeLine(" done.\n", report)

    # Status must be: OUT=1, IN=0, STS=1 (OUT)
    report = writeLine('  {0}) Checking limit switches:\n'.format(stepCount), report)
    stepCount = stepCount + 1
    outValue = outPv.get()
    outValueStr = outPv.get(as_string=True)
    inValue = inPv.get()
    inValueStr = inPv.get(as_string=True)
    statusValue = statusPv.get()
    statusValueStr = statusPv.get(as_string=True)
    
#    expectedOutValue = 1
#    expectedInValue = 0
#    expectedStatusValue = 1
    if (expectedOutValue == outValue and
        expectedInValue == inValue and
        expectedStatusValue == statusValue):
        report = writeLine("     Got correct limit switch values\n", report)
        report = writeLine('     {0}={1} ({2})\n'.
                           format(outPv.pvname, outValue, outValueStr), report)
        report = writeLine('     {0}={1} ({2})\n'.
                           format(inPv.pvname, inValue, inValueStr), report)
        report = writeLine('     {0}={1} ({2})\n'.
                           format(statusPv.pvname, statusValue, statusValueStr), report)
    else:
        report = writeLine("  *** ERROR ***\n", report)
        report = writeLine('     {0}={1} ({2}) [expected {3}]\n'.
                           format(outPv.pvname, outValue, outValueStr,
                                  expectedOutValue), report)
        report = writeLine('     {0}={1} ({2}) [expected {3}]\n'.
                           format(inPv.pvname, inValue, inValueStr,
                                  expectedInValue), report)
        report = writeLine('     {0}={1} ({2}) [expected {3}]\n'.
                           format(statusPv.pvname, statusValue,
                                  statusValueStr, expectedStatusValue), report)
        failures.append('{0} {1} FAILED (step {2})\n'.
                        format(deviceName, operationName, stepCount))

    return report, failures, stepCount

# Target Status Values (TGT_STS: 0-Moving, 1-Out, 2-In, 3-Inconsistent)
# e.g. testDevice("Target", "TGT", "PROF:B34:300")
def testInsertionDevice(deviceName, devicePvSuffix, pvBase, report, failures, stepCount):
    report = writeLine('### Testing {0} device ###\n'.format(deviceName), report)
    outPv = PV(pvBase + ":" + devicePvSuffix + "_OUT")
    inPv = PV(pvBase + ":" + devicePvSuffix + "_IN")
    statusPv = PV(pvBase + ":" + devicePvSuffix + "_STS")
    controlPv = PV(pvBase + ":" + devicePvSuffix + "_CTRL")

    report, failures, stepCount = \
    testInsertionDeviceOperation(deviceName, 'Remove', 1, 0, 1, 0,
                                 outPv, inPv, statusPv, controlPv,
                                 report, failures, stepCount)
    report, failures, stepCount = \
    testInsertionDeviceOperation(deviceName, 'Insert', 0, 1, 2, 1,
                                 outPv, inPv, statusPv, controlPv,
                                 report, failures, stepCount)
    report, failures, stepCount = \
    testInsertionDeviceOperation(deviceName, 'Remove', 1, 0, 1, 0,
                                 outPv, inPv, statusPv, controlPv,
                                 report, failures, stepCount)

    return report, failures, stepCount

parser = argparse.ArgumentParser(description='Profile Monitor Test Script')
parser.add_argument('d', metavar='device_name', type=str, nargs=1,
                    help='PV name for the channel to be tested (e.g. PROF:B34:100')
parser.add_argument('i', metavar='vioc_name', type=str, nargs=1,
                    help='Name of VIOC controlling test chassis (e.g. VIOC:B34:PC01')
parser.add_argument('--l', dest='lamp', action='store_const',
                    default=False, const=sum,
                    help='Test lamps only - turn lamp on, vary brightness, turn off')
parser.add_argument('--t', dest='target', action='store_const',
                    default=False, const=sum,
                    help='Test target only - ' +
                    'insert/remove target, verify limit switches')
parser.add_argument('--f', dest='filters', action='store_const',
                    default=False, const=sum,
                    help='Test filters only -' +
                    'insert/remove filters, verify limit switches')
parser.add_argument('--m', dest='motors', action='store_const',
                    default=False, const=sum,
                    help='Test lens motors only (zoom/iris/focus) ' +
                    '- move clockwise/counter clockwise')
parser.add_argument('--c', dest='camera', action='store_const',
                    default=False, const=sum,
                    help='Test camera power (on/off)')
parser.add_argument('--a', dest='all', action='store_const',
                    default=False, const=sum,
                    help='Perform all tests')
parser.add_argument('-j', metavar='channel_number', type=int,
                    nargs=1, required=True,
                    help='Chassis channel number (1 through 4)')
parser.add_argument('-s', metavar='chassis_serial', type=int,
                    nargs=1, required=True,
                    help='Chassis serial number')
parser.add_argument('--r', dest='report', action='store_const',
                    default=False, const=sum,
                    help='Generate test report (must also specify --a option)')

args = parser.parse_args()

if (args.report and args.all):
    reportFileName="Chassis-{0}-Channel-{1}-test-report".format(args.s[0], args.j[0])
    f = open(reportFileName + ".txt", "w")

failures=[]
stepCount=1

report = writeLine("===================================================\n", "\n")
report = writeLine("=== LCLS-II Profile Monitor Chassis Test Script\n", report)
report = writeLine('=== Chassis: {0}\n'.format(args.s[0]), report)
report = writeLine('=== Channel: {0}\n'.format(args.j[0]), report)
report = writeLine('=== Date: {0}\n'.format(str(datetime.datetime.now())), report)
report = writeLine('=== User: {0}\n'.format(getpass.getuser()), report)
report = writeLine("===================================================\n", report)
report = writeLine("\n", report)

if (args.lamp):
    report, failures, stepCount = \
        testLamp('Target', 'TGT', args.d[0], args.i[0], report, failures, stepCount)

    report, failures, stepCount = \
        testLamp('Grid', 'GRID', args.d[0], args.i[0], report, failures, stepCount)

if (args.target):
    report, failures, stepCount = \
        testInsertionDevice('Target', 'TGT', args.d[0], report, failures, stepCount)

if (args.filters):
    report, failures, stepCount = \
        testInsertionDevice('Filter #1', 'FLT1',
                            args.d[0], report, failures, stepCount)
    report = writeLine("\n", report)

    report, failures, stepCount = \
        testInsertionDevice('Filter #2', 'FLT2',
                            args.d[0], report, failures, stepCount)

if (args.motors):
    report, failures, stepCount = \
        testMotor('Iris', 1, args.d[0], report, failures, stepCount)
    report = writeLine("\n", report)

    report, failures, stepCount = \
        testMotor('Zoom', 2, args.d[0], report, failures, stepCount)
    report = writeLine("\n", report)

    report, failures, stepCount = \
        testMotor('Focus', 3, args.d[0], report, failures, stepCount)

if (args.camera):
    report, failures, stepCount = \
        testCamera(args.d[0], report, failures, stepCount)

if (args.all):
    report, failures, stepCount = \
        testInsertionDevice('Target', 'TGT', args.d[0], report, failures, stepCount)
    report = writeLine("\n", report)

    report, failures, stepCount = \
        testInsertionDevice('Filter #1', 'FLT1',
                            args.d[0], report, failures, stepCount)
    report = writeLine("\n", report)

    report, failures, stepCount = \
        testInsertionDevice('Filter #2', 'FLT2',
                            args.d[0], report, failures, stepCount)
    report = writeLine("\n", report)

    report, failures, stepCount = \
        testLamp('Target', 'TGT',
                 args.d[0], args.i[0], report, failures, stepCount)
    report = writeLine("\n", report)

    report, failures, stepCount = \
        testLamp('Grid', 'GRID',
                 args.d[0], args.i[0], report, failures, stepCount)
    report = writeLine("\n", report)

    report, failures, stepCount = \
        testMotor('Iris', 1, args.d[0], report, failures, stepCount)
    report = writeLine("\n", report)

    report, failures, stepCount = \
        testMotor('Zoom', 2, args.d[0], report, failures, stepCount)
    report = writeLine("\n", report)

    report, failures, stepCount = \
        testMotor('Focus', 3, args.d[0], report, failures, stepCount)
    report = writeLine("\n", report)

    report, failures, stepCount = \
        testCamera(args.d[0], report, failures, stepCount)
    report = writeLine("\n", report)

report = reportTestResult(report, failures)

if (args.report and args.all):
    f.write(report)
    f.close()

    cmd='enscript -p {0}.ps {0}.txt'.format(reportFileName)
    p=subprocess.Popen(cmd, shell=True)
    streamdata=p.communicate()[0]
    rc=p.returncode
    if (rc != 0):
        print 'ERROR: Failed to generate postscript report file: {0}.ps.'.format(reportFileName)
    else:
        cmd='ps2pdf {0}.ps {0}.pdf'.format(reportFileName)
        p=subprocess.Popen(cmd, shell=True)
        streamdata=p.communicate()[0]
        rc=p.returncode
        if (rc != 0):
            print 'ERROR: Failed to generate pdf report file: {0}.ps.'.format(reportFileName)
