#!/usr/bin/python3

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

sys.stdout = open('/tmp/zzz-fiber-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
function = None
jsonStr = None
testPlanIdx = None
while (arguments >= position):
    print ('Parameter %i: %s' % (position, sys.argv[position]))
    if position == 1:
        function = sys.argv[position]
    if position == 2:
        jsonStr = sys.argv[position]
    if position == 3:
        testPlanIdx = sys.argv[position]
    position += 1

if function is None or function not in ['OTDR','OTDR-Y']:
    print ('The function %s provided is not supported!' % (function))
    sys.stdout.close()
    sys.exit(1)
# Minor limitation of this script for v1: CDM test type is not the same thing as ISU functions list content.
# so we are always looking for 'OTDR' (the Expert Singlemode OTDR) with this current code
# (That is enough for now, but we'll need to adapt later)

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)

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

# Obtain the Fiber-ISU port number
srv = ScpiAccess('127.0.0.1', 5025)
ports = None
cnt = 0
while (not ports or ports == '0') and cnt < 5:
    ports = srv.SendAndReadCommand('prtm:list?')
    sleep (0.25)
    cnt += 1
if not ports:
    print ('Failed to obtain Fiber ISU port!')
    sys.exit(1)

print ('Ports returned = %s' % (ports))
port = None
for element in ports.split(','):
    key,value = element.split(':')
    key = key.strip()
    value = value.strip()
    print ('Checking key:%s, value:%s' % (key,value))
    if key == 'Fiber-ISU':
        name,port = key,int(value)
        break

print ('Fiber-ISU port is: %s' % (str(port)))
srv.disconnect()

if port is None:
    print ('Cannot find Fiber ISU port!')
    sys.stdout.close()
    sys.exit(1)

# Check if the FiberOptic is running
foRunning = True
try:
    pidFO = check_output(['pidof', 'Fiber_Optic'])
    print ('FO running with PID: %s' % (pidFO))
except:
    foRunning = False
    print ('FO not running...')

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

#if process already running,
#   just raise it
#else
#   parse homepage content
#   launch otdr script
if foRunning:
    print ('Raise the FiberOptic process')
    Popen(['/acterna/release/bin/cmsend %s' %('guitaskmgr cmd raise_task \"Fiber-UI\"')], shell = True)
    # Do also need to ensure the (Expert-SM) OTDR is turned on in this case too.
    # TBD TODO
else:
    print ('Start the FiberOptic process')
    params = str(port) + ' '
    for pos in ['PWRS', 'OPPS', 'BOTH']:
        found = False
        for slic in ['SLIC1', 'SLIC2', 'SLIC3', 'SLIC4', 'SLIC5', 'SLIC6', 'SLIC7', 'BASE']:
            tmpArg = pos + ',' + slic
            tmpCmd = 'MOD:FUNC:LIST? ' + tmpArg
            tmpReply = isu.SendAndReadCommand(tmpCmd)
            print ('Checking : %s --> %s' % (tmpCmd, tmpReply))
            if function in str(tmpReply):
                print ('Found %s module in %s' % (function, tmpArg))
                params += tmpArg
                otdrPos = tmpArg
                found = True
                break
        if found:
            break

    if not found:
        print ('Cannot determine position and level(slice) for the %s module!' % (function))
        isu.disconnect()
        sys.stdout.close()
        sys.exit(1)

    params += ' '
    params += function
    params += ' ON'
    Popen(['/acterna/release/bin/isu_select_function_with_focus.sh %s' % (params)], shell = True)

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

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

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

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