#!/usr/bin/env python3
# @file testAdvDIO.py
#
# @brief Check the correct reception and sending of packages
#
# @author Manuel Castilla
# @date 25/04/2019
#
###########################################################################

import configparser
from dio import DIO
import time
from ssh import SshCmd,SshCmdException


delay = 0.001
maxOffset = 0.000000008

def findTimestamp(listStamp1,listStamp2,offset):
    """
    This function compare two list and search if two timestamps match

    Args:
        listStamp1: first list of timestamps
        listStamp2: second list of timestamps
        offset: maximum offset between each comparison

    Return:
        True if it find a match in the two lists, False otherwise
    """
    for i in listStamp1:
        for j in listStamp2:
            value = i - j
            if (value <= offset and value >= -offset):
                return True

    return False


def testAdvDIO(hostName1,userName1,password1,interfaceName1,busId1,hostName2,userName2,password2,interfaceName2,busId2):
    """
    Check the pulses generated on a remote board

    Args:
        hostName1: ip remote host 1
        username1: user name host 1
        password1: password
        interfaceName1 : interface name
        busId1: number PCIe bus PC 1
        hostName2: ip remote host 2
        username2: user name host 2
        password2: password
        interfaceName2 : interface name
        busId2: number PCIe bus PC 2
    Raises:
        error test
    """
    try:
        sshCmd1 = SshCmd()
        sshCmd2 = SshCmd()
        dio1 = DIO(hostName1,userName1,password1,busId1)
        dio2 = DIO(hostName2,userName2,password2,busId2)
        dio1.configurePorts("pdiii")
        dio2.configurePorts("iiiii")
        dio1.clearTimestamps()
        dio2.clearTimestamps()
        command = "sudo wr-dio-agent %s /dev/fmc-dio-%i:0" % (interfaceName1,int(busId1,16))
        sshCmd1.exec(hostName1,command,userName1,password1,False)
        command = "sudo wr-dio-ruler %s /dev/fmc-dio-%i:0 IN0 R1+%s" % (interfaceName2,int(busId1,16),str(delay))
        sshCmd2.exec(hostName2,command,userName2,password2,False)
        totalOffset = delay + maxOffset
        time.sleep(2)
        if(not findTimestamp(dio1.getTimestamp(0),dio1.getTimestamp(1),totalOffset)):
            raise
    except SshCmdException as e:
        SshCmd.printSshErrorCommand(e.strError,command)
        raise
    except:
        print("Test advanced error")
        raise


#--------------------------------------------------#
#--------------------------------------------------#
# MAIN
#--------------------------------------------------#
#--------------------------------------------------#

def main(configuration):
    hostName1 = configuration["hostName1"]
    userName1 = configuration["userName1"]
    password1 = configuration["password1"]
    interfaceName1 = configuration["interfaceName1"]
    busIdSpec1 = configuration["busIdSpec1"]
    hostName2 = configuration["hostName2"]
    userName2 = configuration["userName2"]
    password2 = configuration["password2"]
    interfaceName2 = configuration["interfaceName2"]
    busIdSpec2 = configuration["busIdSpec2"]

    try:
        print("\nExecuting advanced DIO test")
        print("This test needs White Rabbit working")
        testAdvDIO(hostName1,userName1,password1,interfaceName1,busIdSpec1,hostName2,userName2,password2,interfaceName2,busIdSpec2)
        print("Test advanced DIO: successful")
    except:
        print("Test advanced DIO: error")

if __name__ == '__main__':
    try:
        configuration = {}
        nameConfig = "configuration.cfg"

        config = configparser.ConfigParser()
        config.readfp(open(nameConfig))

        configuration["hostName1"] = config.get('pc1',"hostName")
        configuration["userName1"] = config.get('pc1',"userName")
        configuration["password1"] = config.get('pc1',"password")
        configuration["interfaceName1"] = config.get('pc1',"interfaceName")
        configuration["busIdSpec1"] = config.get('pc1',"busIdSpec")
        configuration["hostName2"] = config.get('pc2',"hostName")
        configuration["userName2"] = config.get('pc2',"userName")
        configuration["password2"] = config.get('pc2',"password")
        configuration["interfaceName2"] = config.get('pc2',"interfaceName")
        configuration["busIdSpec2"] = config.get('pc2',"busIdSpec")

        main(configuration)
    except configparser.Error as e:
        print("Error load configuration:",e.message)
