#!/usr/bin/python3

# Script only suited to the mts family

import sys
import json
from subprocess import check_output, Popen
from time import sleep
from viavi.mts.ScpiAccess import ScpiAccess

sys.stdout = open('/tmp/mts-inspection-launch.log', 'w')

# Count the arguments
arguments = len(sys.argv) - 1
print ('The script %s is called with %i arguments' % (sys.argv[0], arguments))

# Output arguments
position = 1
cdmFunction = None
jsonStr = None
testPlanIdx = None
testLocIdx = None
while (arguments >= position):
    print ('Parameter %i: %s' % (position, sys.argv[position]))
    if position == 1:
        cdmFunction = sys.argv[position]
    if position == 2:
        jsonStr = sys.argv[position]
    if position == 3:
        testPlanIdx = sys.argv[position]
    if position == 4:
        testLocIdx = sys.argv[position]
    position += 1

# Test against CDM test.type values that we manage with this script (not the ISU/FO function names)
# (CDM test type is not the same thing as ISU functions list content)
if cdmFunction is None or cdmFunction not in ['fiberInspection']:
    print ('The cdm test type %s requested is not supported!' % (cdmFunction))
    sys.stdout.close()
    sys.exit(1)

if jsonStr is None:
    print ('Empty or no json provided!')
    sys.stdout.close()
    sys.exit(1)

if testPlanIdx is None:
    print ('No test plan index provided!')
    sys.stdout.close()
    sys.exit(1)

if testLocIdx is None:
    print ('No test locations index provided - assuming 0')
    testLocIdx = 0

jsonContent = json.loads(jsonStr)
print ('Parameter JSON:\n%s\n' % (json.dumps(jsonContent, indent=4, sort_keys=False)))


# Check if the Microscope App is running
micRunning = True
try:
    pidMic = check_output(['pidof', 'Microscope'])
    print('Microscope running with PID: %s' % (pidMic))
except:
    micRunning = False
    print('Microscope not running...')

#ISU port number
port = 8000
# Connecting to ISU port and sending SCPI commands
isu = ScpiAccess('127.0.0.1', port)

isuFunction = 'MICROSCOPE'
# Determine which ISU function is needed for a particular CDM test type
testType = jsonContent.get('type', '')
config = jsonContent.get('configuration', '')
if testType == 'fiberInspection':
    print( 'Launching a Fiber Inspection test')
    isuFunction = 'MICROSCOPE'

# Need to check homepage content to establish if the required function is available AND already turned **ON**
# Check if there is a Microscope plugged in
found = False
tmpCmd = 'MOD:FUNC:LIST? BOTH,BASE'
tmpReply = isu.SendAndReadCommand(tmpCmd)
print('Checking : %s --> %s' % (tmpCmd, tmpReply))
if isuFunction in str(tmpReply):
    print('Found Microscope')
    found = True


if not found:
    print ('Microscope not plugged in')
    isu.disconnect()
    sys.stdout.close()
    sys.exit(1)


# Now select the function (turn it on)
fncmd = 'MOD:FUNC:SEL BOTH,BASE' + ',"%s"' % (isuFunction) + ', ON'
print ('Selecting function, cmd: \n%s' % (fncmd))
isu.SendCommand(fncmd)
# and update the current function
currentcmd = 'MOD:FUNC:CURR BOTH,BASE' + ',"%s"' % (isuFunction)
print ('Current function, cmd: \n%s\n' % (currentcmd))
isu.SendCommand(currentcmd)
# + Need to force focus away from IJM


# Waiting until the Microscope App is started and initialized
ret = isu.SendAndReadCommand('PROC:STAT? "Microscope"')
while ret.find('ACTIVATED') < 0:
    print ('Microscope not activated yet - %s' % (ret))
    sleep(0.25)
    ret = isu.SendAndReadCommand('PROC:STAT? "Microscope"')

# Above is good first step but not enough to be certain the Microscope is turned on
# Wait until select query returns ON
tmpCmd = 'MOD:FUNC:SEL? BOTH,BASE' + ',"%s"' % (isuFunction)
print('Querying state: %s' % (tmpCmd))
ret = isu.SendAndReadCommand(tmpCmd)
while ret.find('ON') < 0:
    print ('Microscope not selected yet - %s' % (ret))
    sleep(0.25)
    print ('Querying state: %s' % (tmpCmd))
    ret = isu.SendAndReadCommand(tmpCmd)

# Execute the SCPI command that passes all needed parameters to Fiber_Optic
cmd = 'WORK:TPIL ' + str(testPlanIdx) + "," + str(testLocIdx) + ",'" + str(jsonStr) + "'"
print ('Sending cmd: \n%s\n' % (cmd))
isu.SendCommand(cmd)

print ('\nDONE\n')
isu.disconnect()
sys.stdout.close()
sys.exit(0)
