#!/usr/bin/python3
import sys
from subprocess import check_output
from viavi.mts.ScpiAccess import ScpiAccess

sys.stdout = open('/tmp/fiber-can-launch.log', 'w')
try:
    # 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
    jsonStr = None
    while arguments >= position:
        print("Parameter %i: %s" % (position, sys.argv[position]))
        if position == 2:
            jsonStr = sys.argv[position]
        position = position + 1

    # ISU port number
    port = 8000
    # Check if the FiberOptic is running
    try:
        pidFO = check_output(['pidof', 'Fiber_Optic'])
        print('FO running with PID: %s' % (pidFO))
    except Exception as err:
        print('FO not running...')  # @TODO remove this when prepared for delivery
        sys.stdout.close()
        sys.exit(1)

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

    # Check that the OTDR module is available
    found = False
    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))
            for isuFunction in ['OTDR', 'TESTPRO', 'TRUE-FIBER', "OTDR-Y"]:
                if isuFunction in str(tmpReply):
                    print('Found %s function available at %s' % (isuFunction, tmpArg))
                    params += tmpArg
                    otdrPos = tmpArg
                    found = True
                    # This means we are always using the *First* one found (even if a second possibility is already ON)
                    break
            if found:
                break
        if found:
            break

    if not found:
        print("ERROR_MODULE^OTDR")
        print("Test requires an OTDR module. Ensure the module is properly attached.")
        sys.stdout.close()
        sys.exit(1)
    else:
        print("OTDR module detected, continuing...")
except Exception as err:
    print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> %s" % str(err))

sys.stdout.close()
sys.exit(0)
