#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys

import os, time, signal
import subprocess

import platform

using_distro = False

try :
    import distro
    using_distro = True
except ImportError :
    pass



import faster_module_path
import py_fastersys

from py_fastersys_enum import *

amc_ip            = ""
amc_mac           = ""

DB1_type          = 0
DB2_type          = 0
Mother_type       = 0

error             = False
ping_timeout      = 0

fpga1             = None
fpga2             = None

caras_node_list  = [ 1, 2, 3, 6, 8, 10, 14, 15, 17, 20 ]
mosahr_node_list = [ 4, 16 ]

##############################################
def exit_gracefully(signum, frame):
    fpga1.Send_Synchro_Stop ()
    fpga2.Send_Synchro_Stop ()
    n3tm.Send_Synchro_Stop  ()
    fpga1.Send_Synchro_Stop ()
    fpga2.Send_Synchro_Stop ()
    n3tm.Send_Synchro_Stop  ()
    daq.Stop                ()
    sys.exit(1)

##############################################
def get_mac_from_ip (arg) :
    ip     = arg
    mac    = ""
    if using_distro :
        ubuntu_distribution = distro.codename ()
        if (ubuntu_distribution != "xenial") :
                cmd    = "netstat -ie | grep -F3 " + ip + " | grep ether | awk '{print $2}'"
        else :
                cmd    = "netstat -ie | grep -B1 " + ip + " | head -n1 | awk '{print $5}'"
    else :
        ubuntu_distribution = platform.dist ()
        if (ubuntu_distribution [2] != "xenial")  :
                cmd    = "netstat -ie | grep -F3 " + ip + " | grep ether | awk '{print $2}'"
        else :
                cmd    = "netstat -ie | grep -B1 " + ip + " | head -n1 | awk '{print $5}'"

    answer = subprocess.check_output     (cmd, shell=True).decode ()
    if (answer.count (":") == 5) :
        mac =  answer.replace ("\n","")
    else :
        cmd = "ping -c 1 " + ip
        try :
            answer =  subprocess.check_output (cmd, shell=True).decode ()
            cmd = "arp -a | grep "+ ip + "[^0-9]| awk \'{print $4}\'"
            answer =  subprocess.check_output (cmd, shell=True).decode ()
            if (answer.count (":") == 5) :
                mac = answer.replace ("\n","")
        except :
            mac  = ""
    return mac


##############################################
def module_ping (ip) :
    answer = True
    nodes  = 0

    if (ip == "192.168.1.204"):
        nodes = 2
    else:
        nodes = 3
    for i in range (0,nodes) :
       result_ping = py_fastersys.Ping (ip , i)
       clock = result_ping          ["Clock"]
       mother= Whoswho_Mother.Image [result_ping ["Mother"]]
       node  = Whoswho_Node.Image   [result_ping ["Node"  ]]
       if (mother != "UNKNOWN") :
           if i == 0 :
              print("==> Faster Ping " + '{:14}'.format (ip))
           else :
              print('{:-<30}'.format("                |") + str(i) + " => clock : " + '{:.9f}'.format(clock) + " s  " + mother  + "   " + node)
       else :
           answer = False
           if i == 0 :
              print("Faster Ping " + '{:14}'.format (ip)  + str(i) + " => timeout")
           else :
              print('{:-<39}'.format("                |") + str (i) + " => timeout")
    return answer
##############################################

def check_ping (ip) :
    answer = True
    error  = 0

    for y in range (0,1000):
        for i in range (0,3) :
           result_ping = py_fastersys.Ping (ip , i)
           clock = result_ping          ["Clock"]
           mother= Whoswho_Mother.Image [result_ping ["Mother"]]
           node  = Whoswho_Node.Image   [result_ping ["Node"  ]]
           if (mother != "UNKNOWN") :
               if i == 0 :
                  print(("==> Faster Ping n°" + str(y) + " IP = " + '{:14}'.format (ip)))
               else :
                  print(('{:-<30}'.format("                |") + str(i) + " => clock : " + '{:.9f}'.format(clock) + " s  " + mother  + "   " + node))
           else :
               if i == 0 :
                  print(("Faster Ping n°" + str(y) + " IP = " + '{:14}'.format (ip)  + str(i) + " => timeout"))
               else :
                  print(('{:-<39}'.format("                |") + str (i) + " => timeout"))
               error = error + 1
               if (error > 10 ) :
                   return error
    return error


##############################################
def node_check (ip) :
    answer = True
    for i in range (1,3) :
        for y in range (0,10):
           result_ping = py_fastersys.Ping (ip , i)
           clock = result_ping          ["Clock"]
           mother= Whoswho_Mother.Image [result_ping ["Mother"]]
           node  = Whoswho_Node.Image   [result_ping ["Node"  ]]
           if (mother == "UNKNOWN") :
               print(("==> Faster reset number " + str(y) + " for node n°" + str(i) + " IP = " + '{:14}'.format (ip)))
               py_fastersys.Reset_Node (ip, i)
               time.sleep (0.1)
           else :
               break
    return True


##############################################
def hardware_check () :
    global DB1_type
    global DB2_type
    global Mother_type
    global amc_ip
    error = False

    try:
        M_EE        = py_fastersys.Mother_Eeprom_Read (amc_ip)
        Mother_type = Whoswho_Mother.Image.index (Eeprom_Mother_Board (M_EE))
        if (Mother_type == 0):
            error = True
            print("==> Mother_board eeprom read error")
            Mother_type = 4
    except:
        error = True
        print("==> Mother_board eeprom read error")

    if (py_fastersys.Is_FPGA_Revision_Number_Ok (amc_ip, 0)) :
        print("==> The version of the FPGA0 is Ok")
    else:
        print("==> Use faster_hardware_shell to upgrade the FPGA0 firmware")
        print("")
        sys.exit (1)

    try :

        DB_EE1      = py_fastersys.Daughter_Eeprom_Read (amc_ip, 1)
        DB1_type    = Eeprom_Daughter_Board (DB_EE1)

    except :
        error = True
        print("==> Daughter_board eeprom 1 read error")

    try:

        DB_EE2      = py_fastersys.Daughter_Eeprom_Read (amc_ip, 2)
        DB2_type    = Eeprom_Daughter_Board (DB_EE2)

    except :
        error = True
        print("==> Daughter_board eeprom 2 read error")

    if (DB1_type == "UNKNOWN"):
        print("==> Daughter_board 1 is missing")
        error = True

    if (DB2_type == "UNKNOWN"):
        print("==> Daughter_board 2 is missing")
        error = True

    #if (error == True):
    #   DB1_type = "CARAS"
    #   DB2_type = "CARAS"


##############################################
def hardware_load  () :
    global fpga1
    global fpga2
    global amc_ip
    global ping_timeout

    for node in mosahr_node_list :
        print(("==> Downloading fpga1 firmware : " + Whoswho_Node.Image [node]))
        py_fastersys.Pre_Load    (Mother_type, amc_ip, 1, node)
        print(("==> Downloading fpga2 firmware : " + Whoswho_Node.Image [node]))
        py_fastersys.Pre_Load    (Mother_type, amc_ip, 2, node)
        time.sleep               (1)
        py_fastersys.Load        (amc_ip)
        time.sleep               (3)
        answer = subprocess.check_output("faster_ping " + amc_ip  + " 0 --verbose | awk \'{print$10}\'", shell=True).decode ()
        if (answer.count ("AMC_C5")) :
            py_fastersys.Reset_Nodes (amc_ip)
            counter = 0
            time.sleep               (3)
            while ((module_ping (amc_ip) == False) or (counter == 5)) :
               py_fastersys.Reset_Nodes (amc_ip)
               time.sleep               (3)
               counter = counter + 1
        if (check_ping (amc_ip) != 0) :
           sys.exit (1)
    for node in caras_node_list :
        print(("==> Downloading fpga1 firmware : " + Whoswho_Node.Image [node]))
        py_fastersys.Pre_Load    (Mother_type, amc_ip, 1, node)
        print(("==> Downloading fpga2 firmware : " + Whoswho_Node.Image [node]))
        py_fastersys.Pre_Load    (Mother_type, amc_ip, 2, node)
        time.sleep               (1)
        py_fastersys.Load        (amc_ip)
        time.sleep               (3)
        answer = subprocess.check_output("faster_ping " + amc_ip  + " 0 --verbose | awk \'{print$10}\'", shell=True).decode ()
        if (answer.count ("AMC_C5")) :
            py_fastersys.Reset_Nodes (amc_ip)
            counter = 0
            time.sleep               (3)
            while ((module_ping (amc_ip) == False) or (counter == 5)) :
               py_fastersys.Reset_Nodes (amc_ip)
               time.sleep               (3)
               counter = counter + 1
        if (check_ping (amc_ip) != 0) :
           sys.exit (1)


##############################################
##############################################

if __name__ == "__main__":


    print("")

    if (len (sys.argv) != 2) :
        print(("==> Usage :  " + sys.argv[0] + " IP_Module "))
        print("")
        sys.exit (1)

    signal.signal(signal.SIGINT, exit_gracefully)

    # DAQ Config
    error        = False
    channel_list = []
    daq_ip       = "192.168.0.1"
    daq_mac      =  get_mac_from_ip (daq_ip)

    if (daq_mac.count (":") != 5) :
        print("==> No FASTER network found, connect your hardware")
        print("")
        sys.exit (1)

    amc_ip            = sys.argv[1]
    amc_mac           = get_mac_from_ip (amc_ip)

    if (amc_mac.count (":") != 5) :
        print(("==> Board IP = " + amc_ip + " is unreacheable"))
        print("")
        sys.exit (1)

    hardware_check ()
    hardware_load  ()

    print(("==> The number of timeout is " + str (ping_timeout)))
    print("")

