#!/usr/bin/env python3
# @file testWR.py
#
# @brief
#
# @author Manuel Castilla
# @ingroup
# @date 23/04/2019
#
###########################################################################

from vuart import Vuart
import configparser
import time


def whoIsMaster(hostName,userName,password,busId):
    """
    This function asks which spec has SFP purple (master)

    Args:
        hostName: ip remote host
        username: user name
        password: password
        busId: number PCIe bus

    Return:
        True if the spec has SFP purple, False otherwise
    """
    ret = False
    try:
        vuart = Vuart(hostName,userName,password,busId)
        value = vuart.sfpDetect()
        if ("AXGE-3454-0531" in value):
            ret = True
    except:
        print("Who is master: error, host:",hostName)
        raise

    return ret

def putMode(hostName,userName,password,busId,mode):
    """
    This function puts in mode master an spec

    Args:
        hostName: ip remote host
        username: user name
        password: password
        busId: number PCIe bus
        mode: mode ptp status("master","slave")

    Raises:
        error function
    """
    try:
        vuart = Vuart(hostName,userName,password,busId)
        if (mode == "master"):
            vuart.modeMaster()
        else:
            vuart.modeSlave()

        vuart.ptpStart()
        value = vuart.mode()
        if(mode in value):
            print("Put mode", mode,": ok, host:",hostName)
        else:
            raise
    except:
        print("Put mode: error, host:",hostName)
        raise


def checkTrackPhase(hostName,userName,password,busId):
    """
    This function check if the state is TRACK_PHASE

    Args:
        hostName: ip remote host
        username: user name
        password: password
        busId: number PCIe bus
    Raises:
        error function
    """
    try:
        vuart = Vuart(hostName,userName,password,busId)
        numberTimesTry = 10
        i = 0
        while not vuart.isTrackPhase():
            if (i == numberTimesTry):
                raise
            i = i + 1
            time.sleep(1)
        print("Track Phase: ok")
    except:
        print("Track phase: error, host:",hostName)
        raise

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

    try:
        print("Executing WR test")
        masterSpec1 = whoIsMaster(hostName1,userName1,password1,busIdSpec1)
        masterSpec2 = whoIsMaster(hostName2,userName2,password2,busIdSpec2)
        if (masterSpec1 == 1 or masterSpec2 == 1):
            if (masterSpec1 == 1):
                putMode(hostName2,userName2,password2,busIdSpec2,"slave")
                putMode(hostName1,userName1,password1,busIdSpec1,"master")
                checkTrackPhase(hostName2,userName2,password2,busIdSpec2)
            else:
                putMode(hostName1,userName1,password1,busIdSpec1,"slave")
                putMode(hostName2,userName2,password2,busIdSpec2,"master")
                checkTrackPhase(hostName1,userName1,password1,busIdSpec1)

            print("Test WR: successful")
        else:
            print("Error: It is not possible to know who is master")
            raise
    except:
        print("Test WR: error")

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

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

        configuration["hostName1"] = config.get('config',"hostName1")
        configuration["userName1"] = config.get('config',"userName1")
        configuration["password1"] = config.get('config',"password1")
        configuration["busIdSpec1"] = config.get('config',"busIdSpec1")
        configuration["interfaceName1"] = config.get('config',"interfaceName1")
        configuration["hostName2"] = config.get('config',"hostName2")
        configuration["userName2"] = config.get('config',"userName2")
        configuration["password2"] = config.get('config',"password2")
        configuration["busIdSpec2"] = config.get('config',"busIdSpec2")
        configuration["interfaceName2"] = config.get('config',"interfaceName2")

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